This recent SO discussion has confused me. The NSMutableArray prototype for addObject: is
- (void)addObject:(id)anObject
and id is defined in objc.h as
typedef struct objc_class *Class;
typedef struct objc_object {
Class isa;
} *id;
When I add an NSObject or subclass to an NSMutableArray, its retain count is incremented, and when I remove it from an NSMutableArray it is decremented. Does this mean that if an id type which is not an NSObject or subclass is added to an NSMutableArray, it has to respond to retain and release messages? The definition of id does not seem to force this. Is it an objective C directive that any id type should respond to standard memory management messages?
The hard truth about most Foundation containers (and by extent most Apple-developed classes, and by extent also most classes developed by third parties) is that when a method accepts the
idtype, it should really readid<NSObject>, which means any type that responds to theNSObjectprotocol. Instances of classes that aren’t part of theNSObjecthierarchy are unlikely to respond to-retainand-release, which is especially inconvenient when trying to add them to a container. They’re also unlikely to respond to-hash,-isEqual:,-description,-copy, and to all the other methods Foundation containers can use on their contents for whatever reason.For instance, if you attempt to add
Classobjects to a Foundation container (other thanNSMapTablesince this one was designed with a lot of flexibility in mind), you’ll hit a wall because “modern” ObjC classes are expected to inherit fromNSObject, or at least implement theNSObjectprotocol.This is a pretty rare situation, though.
Classis pretty much the only useful class around that doesn’t inherit fromNSObject.