What differences exist between Objective-C categories and .NET extension methods?
I'm learning about Categories in Objective-C and they seem really similar to extension methods in .NET.
Are there any subtle differences or gotchas between the two that can cause problems when moving from one language to开发者_JAVA百科 the other, or are they for all intents and purposes identical concepts?
In my experience using the two concepts in C# and ObjC, I use the features for the same problems. Adding new instance or static methods to built-in types when subclassing either isn't allowed or ill advised.
I tend to try and avoid Categories/Extensions because they can be a code smell that you are relying on built-in classes too heavily instead of building your own data structures to represent your system.
With that said, I haven't run into any strange gotchas once you understand the syntactical differences.
In the .NET world, an extension method will be called even if the object instance is null
. For example:
public static class Extensions {
public static string CountCharacters(this string inputString) {
if (inputString == null) return "None!";
return inputString.Length.ToString;
}
}
public void TestExtension() {
string testString = null;
string result = testString.CountCharacters(); // returns "None!"
}
In the Objective-C world, instance methods defined in a category will not be called on an nil
object instance.
@implementation NSString (CountCharacters)
- (NSString *)countCharacters {
if (self)
return [self length];
return @"None!";
}
@end
-(void)testCategoryMethod {
NSString *testString = nil;
NSString *result = [testString countCharacters];
// 'result' will remain nil
}
精彩评论