Summary of the usage of Introspection in objective c

  • 2020-04-02 02:20:59
  • OfStack

Introspection is a powerful feature of object-oriented languages and environments, and objective-c and Cocoa are particularly good at it. Introspection is the ability of an object to reveal detailed information about itself as a runtime object. These details include where the object is on the inheritance tree, whether the object follows a specific protocol, and whether it can respond to specific messages. The NSObject protocol and classes define a number of introspection methods for querying run-time information to identify objects based on their characteristics.

Proper use of introspection can make object-oriented programs more efficient and robust. It also helps to avoid message distribution errors and false assumptions about object equality.

The following sections illustrate how to effectively use NSObject's introspection methods in your code.
 
1, isKindOfClass: Class

Check whether the object is instantiated by that class or its inheritance class

2, isMemberOfClass: Class

Verify that the object is instantiated for that class but not for the inherited class

Example:

The objective-c code is as follows:


if ([item isKindOfClass:[NSData class]]) { 
  const unsigned char *bytes = [item bytes]; 
  unsigned int length = [item length]; 
  // ... 
} 
 

If item is an instantiated object of the NSMutableData class, which is a subclass of the NSData class, the value of [item isKindOfClass:[NSData class]] is also TRUE, and the value of [item isMemberOfClass:[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: the selector

Check whether the object contains this method

The objective-c code is as follows:


- (void)doCommandBySelector:(SEL)aSelector { 
  if ([self respondsToSelector:aSelector]) { 
    [self performSelector:aSelector withObject:nil]; 
  } else { 
    [_client doCommandBySelector:aSelector]; 
  } 
} 

4, conformsToProtocol: protocol

Check whether the object conforms to the protocol and implements all the required methods in the protocol.

The objective-c code is as follows:


// ... 
if (!([((id)testObject) conformsToProtocol:@protocol(NSMenuItem)])) { 
  NSLog(@"Custom MenuItem, '%@', not loaded; it must conform to the 
    'NSMenuItem' protocol.n", [testObject class]); 
  [testObject release]; 
  testObject = nil; 
}

Related articles: