Can you explain "An instance method you define in a category of the NSObject class might be performed not only by instances but by class objects as well", i have come across this sentence while reading an Objective C guide...! But i am not able to get it.
views:
15answers:
1Instance method is a method you can call on an object (as opposed to a class). Each object is an instance of a certain class (just as each of us is an instance of a human1), that’s why we talk about instance methods. For example when you say [someArray count]
, you are calling an instance method called count
on some array object (= instance of the NSArray
class).
Class methods are called on classes, for example [UIApplication sharedApplication]
is a class method of the UIApplication
class. You can’t call an instance method on a class, nor can you call a class method on an object.
Category is a way to extend behaviour of existing classes, a kind of plugin you stick on an existing class. For example by writing this:
@interface NSObject (SampleCategory)
- (void) sayFoo;
@end
@implementation NSObject (SampleCategory)
- (void) sayFoo {
NSLog(@"Foo!");
}
@end
…you make it possible to call [anObject sayFoo]
on any object derived from NSObject
. And now we are getting to the point of the sentence: NSObject
seems to be special, because when you declare an instance method of NSObject
using a category (such as our sayFoo
), you can call this method even as a class method: [NSObject sayFoo]
, [NSView sayFoo]
, etc.
1] Sorry, Googlebot!