Saturday, 7 September 2013

Objective-C category compared to features in other languages

Objective-C category compared to features in other languages

I am trying to draw parallels between Objective-C Category and features in
Java and Ruby. Please see if these conclusions are accurate -
Objective-C Category adds new methods to an existing class even when you
do not have access to source code of the class. Java does not have
anything similar but in Ruby you can "open" any class, including core
language class like String.
class String
def my_new_method
"new test method"
end
end
"some string".my_new_method
=> "new test method"
Similarly in Objective-C - you can "re-open" the NSString class using
category.
#import "NSString+ForTest.h"
@implementation NSString (ForTest)
-(NSString*) myNewMethod {
return @"new test method";
}
@end
However, one difference I see is that, in Ruby, once a class is opened and
modified within a runtime, ALL subsequent uses of that class are affected,
in other words it is a system wide change, while in Objective-C only code
that imports this header file (and any subclasses) are affected. Are there
any other differences?

No comments:

Post a Comment