Objective-C Introspection and introspection
Introspection is a powerful feature of the object-oriented language and environment. Objective-C and Cocoa are particularly rich in this aspect. Through introspection, You can dynamically query the attributes declared in the class and their names and types. Introspection is the ability of an object to reveal its details as a runtime object. These details include the location of the object on the inheritance tree, whether the object complies with a specific protocol, and whether it can respond to a specific message. The NSObject protocol and class define many introspection methods for querying runtime information to identify objects based on their features.
Wise Use of introspection can make Object-oriented Programs more efficient and robust. It helps avoid errors in message distribution, errors in assuming that objects are equal, and similar issues.
The following section describes how to effectively use NSObject's introspection method in code.
1. isKindOfClass: Class
Check whether the object is the class or the object whose inherited class is instantiated.
2. isMemberOfClass: Class
Check whether the object is the class but does not include the object instantiated by the inherited class.
Example:
Objective-c code
1 if ([item isKindOfClass:[NSData class]]) { 2 const unsigned char *bytes = [item bytes]; 3 unsigned int length = [item length]; 4 // ... 5 }
If the item is an object instantiated by the NSMutableData class and the class is a subclass of the NSData class, the value of [item isKindOfClass: [NSData class] is TRUE, while that of [item isMemberOfClass: the value of [NSData class] is False.
If item is an object instantiated by the NSData class, the value of [item isMemberOfClass: [NSData class] is TRUE.
3. respondToSelector: selector
Check whether the object contains this method
Objective-c code
1 - (void)doCommandBySelector:(SEL)aSelector { 2 if ([self respondsToSelector:aSelector]) { 3 [self performSelector:aSelector withObject:nil]; 4 } else { 5 [_client doCommandBySelector:aSelector]; 6 } 7 }
4. conformsToProtocol: protocol
Check whether the object complies with the Protocol and whether all the required methods in the Protocol are implemented.
Objective-c code
1 if ([item isKindOfClass:[NSData class]]) { 2 const unsigned char *bytes = [item bytes]; 3 unsigned int length = [item length]; 4 // ... 5 } 6 if ([item isKindOfClass:[NSData class]]) { 7 const unsigned char *bytes = [item bytes]; 8 unsigned int length = [item length]; 9 // ... 10 }