The Secret Life of NSObject

Because every class inherits from NSObject, it’s worth taking some time to investigate and understand NSObject. NSObject is constructed in a rather elaborate way:

  • It defines some native class methods and instance methods having mostly to do with the basics of instantiation and of method sending and resolution. (See the NSObject Class Reference.)
  • It adopts the NSObject protocol. This protocol declares instance methods having mostly to do with memory management, the relationship between an instance and its class, and introspection. Because all the NSObject protocol methods are required, the NSObject class implements them all. (See the NSObject Protocol Reference.) This architecture is what permits NSProxy to be a root class; it, too, adopts the NSObject protocol.
  • It implements convenience methods related to the NSCopying, NSMutableCopying, and NSCoding protocols, without formally adopting those protocols. NSObject intentionally doesn’t adopt these protocols because this would cause all other classes to adopt them, which would be wrong. But thanks to this architecture, if a class does adopt one of these protocols, you can call the corresponding convenience method. For example, NSObject implements the copy instance method, so you can call copy on any instance, but you’ll crash unless the instance’s class adopts the NSCopying protocol and implements copyWithZone:.
  • A large number of methods are injected into NSObject by more than two dozen informal protocols, ...

Get Programming iOS 4 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.