tags:

views:

15

answers:

1

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.

+1  A: 

Instance 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!

zoul
Ok, fine. It works for both NSObject class and NSObject reference variable.but I am not getting why it works as class Method ??
Matrix
Are you one-hundred-cast-in-concrete percent sure you know the difference between objects, instances, and classes? Or maybe I’m not getting something?
zoul