How to understand NSObject, it is both protocol and interface
Question
You can see following in NSObject.h file
// 1. here is a protocol
@protocol NSObject
// 2. here is an interface, conforming to the above protocol
@interface NSObject <NSObject> {
...
// 3. what is the meaning of "( )" below? NSCoderMethods is a protocol
@interface NSObject (NSCoderMethods)
NSObject is so important that I need to understand, why is it designed like this?
Solution
1.
It is a class (interface) because all concrete classes in ObjC nowadays inherit implementations from NSObject, to support features such as reference-counting and run-time type checking.
2.
Now for the protocol... it exists because NSObject is not the only root class that supports the -retain
and -performSelector:
etc methods.
One important class is NSProxy, which acts as a proxy to forward messages to some actual objects.
The targets of NSProxy are usually NSObjects, so the interface should also support -retain
and -performSelector:
etc methods. But NSProxy cannot inherit from NSObject because there is no is-a relationship between the two.
To express the sibling relationship, both are made to adopt the same protocol, which, unfortunately, also called NSObject.
Making NSObject a protocol also has an advantage that, user-defined protocols can request adopters to support all usual NSObject operations by
@protocol Foo <NSObject>
...
3.
It's a category, which adds extra method implementations to NSObject.