Is it safe to use isKindOfClass: against an NSString instance to determine type?

The warning in the documentation uses the NSMutableArray example. Suppose some developer uses NSMutableArray as base class for his own implementation of a new kind of array CoolFunctioningArray. This CoolFunctioningArray by design is not mutable. However, isKindOfClass will return YES to isKindOfClass:[NSMutableArray class], which is true, but by design is not.

isKindOfClass: will return YES if the receiver somewhere inherits from the class passed as argument. isMemberOfClass: will return YES only if the receiver is an instance of the class passed as argument only, i.e. not including subclasses.

Generally isKindOfClass: is not safe to use to test for membership. If an instance returns YES for isKindOfClass:[NSString class], you know only that it will respond to all methods defined in the NSString class, but you will not know for sure what the implementation of those methods might do. Someone might have subclassed NSString to raise an exception for the length method.

I think you could use isKindOfClass: for this kind of testing, especially if you’re working with your own code which you (as a good Samaritan) designed in such a way it will respond in a way we all expect it to (e.g. the length method of an NSString subclass to return the length of the string it represents instead of raising an exception). If you’re using a lot of external libraries of weird developers (such as the developer of the CoolFunctioningArray, which should be shot) you should use the isKindOfClass method with caution, and preferably use the isMemberOfClass: method (possibly multiple times to test membership of a group of classes).

Leave a Comment