Introspection
Introspection is an object's ability to answer questions about itself at run time: What class are you? Do you inherit from X? Can you handle this message? Do you conform to that protocol? Because Objective-C keeps full class information at run time, these questions are cheap and common, especially when working with id values.
Asking about classes
#import <Foundation/Foundation.h>
@interface Animal : NSObject
@end
@implementation Animal
@end
@interface Bird : Animal
- (void)fly;
@end
@implementation Bird
- (void)fly { NSLog(@"flap flap"); }
@end
int main(void) {
@autoreleasepool {
Bird *robin = [Bird new];
NSLog(@"class: %@", NSStringFromClass([robin class]));
NSLog(@"superclass: %@", NSStringFromClass([robin superclass]));
NSLog(@"isKindOfClass Animal: %d", [robin isKindOfClass:[Animal class]]);
NSLog(@"isKindOfClass NSObject: %d", [robin isKindOfClass:[NSObject class]]);
NSLog(@"isMemberOfClass Animal: %d", [robin isMemberOfClass:[Animal class]]);
NSLog(@"isMemberOfClass Bird: %d", [robin isMemberOfClass:[Bird class]]);
NSLog(@"Bird subclass of Animal: %d", [Bird isSubclassOfClass:[Animal class]]);
}
return 0;
}class: Bird
superclass: Animal
isKindOfClass Animal: 1
isKindOfClass NSObject: 1
isMemberOfClass Animal: 0
isMemberOfClass Bird: 1
Bird subclass of Animal: 1
| Question | Method | YES when |
|---|---|---|
| is it this class or a subclass? | isKindOfClass: |
the object's class is the argument or inherits from it |
| is it exactly this class? | isMemberOfClass: |
the class matches exactly |
| is this class a subclass? | +isSubclassOfClass: |
asked of a class |
Tip: Prefer
isKindOfClass:. Foundation types are class clusters: anNSStringobject is really an instance of a private subclass, so[str isMemberOfClass:[NSString class]]isNOeven for a real string.
Can you handle this message?
respondsToSelector: checks whether an object implements a method, which is exactly what optional protocol methods and duck typing need:
#import <Foundation/Foundation.h>
@interface Bird : NSObject
- (void)fly;
- (void)sing;
@end
@implementation Bird
- (void)fly { NSLog(@"bird flies"); }
- (void)sing { NSLog(@"bird sings"); }
@end
@interface Plane : NSObject
- (void)fly;
@end
@implementation Plane
- (void)fly { NSLog(@"plane flies"); }
@end
int main(void) {
@autoreleasepool {
NSArray *things = @[[Bird new], [Plane new], @"a string"];
for (id thing in things) {
NSString *name = NSStringFromClass([thing class]);
if ([thing isKindOfClass:[NSString class]]) {
name = @"NSString"; // hide the private cluster class name
}
BOOL flies = [thing respondsToSelector:@selector(fly)];
BOOL sings = [thing respondsToSelector:@selector(sing)];
NSLog(@"%@: fly %d, sing %d", name, flies, sings);
if (flies) {
[thing fly];
}
}
NSLog(@"Bird instances respond to sing: %d", [Bird instancesRespondToSelector:@selector(sing)]);
}
return 0;
}Bird: fly 1, sing 1
bird flies
Plane: fly 1, sing 0
plane flies
NSString: fly 0, sing 0
Bird instances respond to sing: 1
Safe handling of mixed data
Data from JSON, property lists or userInfo dictionaries arrives as id. Check types before using them, or a wrong type crashes with "unrecognized selector":
#import <Foundation/Foundation.h>
NSString *describe(id value) {
if ([value isKindOfClass:[NSString class]]) {
return [NSString stringWithFormat:@"string of length %lu", (unsigned long)[value length]];
} else if ([value isKindOfClass:[NSNumber class]]) {
return [NSString stringWithFormat:@"number %.1f", [value doubleValue]];
} else if ([value isKindOfClass:[NSArray class]]) {
return [NSString stringWithFormat:@"array of %lu", (unsigned long)[value count]];
} else if ([value isKindOfClass:[NSDictionary class]]) {
return [NSString stringWithFormat:@"dictionary with keys %@",
[[[value allKeys] sortedArrayUsingSelector:@selector(compare:)] componentsJoinedByString:@","]];
} else if (value == [NSNull null]) {
return @"null";
}
return @"something else";
}
int main(void) {
@autoreleasepool {
NSDictionary *payload = @{@"a_name": @"Zed", @"b_age": @41, @"c_tags": @[@"x", @"y"],
@"d_meta": @{@"v": @2, @"id": @7}, @"e_note": [NSNull null]};
for (NSString *key in [payload.allKeys sortedArrayUsingSelector:@selector(compare:)]) {
NSLog(@"%@ -> %@", key, describe(payload[key]));
}
}
return 0;
}a_name -> string of length 3
b_age -> number 41.0
c_tags -> array of 2
d_meta -> dictionary with keys id,v
e_note -> null
[NSNull null] is a singleton, so comparing with == is correct here.
Classes and selectors from strings
Classes, selectors and protocols can be converted to and from strings, enabling plug-in style code:
#import <Foundation/Foundation.h>
@interface CSVExporter : NSObject
- (NSString *)export;
@end
@implementation CSVExporter
- (NSString *)export { return @"a,b,c"; }
@end
@interface JSONExporter : NSObject
- (NSString *)export;
@end
@implementation JSONExporter
- (NSString *)export { return @"[\"a\",\"b\",\"c\"]"; }
@end
int main(void) {
@autoreleasepool {
for (NSString *format in @[@"CSV", @"JSON", @"XML"]) {
NSString *className = [format stringByAppendingString:@"Exporter"];
Class cls = NSClassFromString(className); // nil if no such class
if (cls) {
id exporter = [cls new];
NSLog(@"%@: %@", className, [exporter export]);
} else {
NSLog(@"%@: not available", className);
}
}
SEL sel = NSSelectorFromString(@"export");
NSLog(@"selector name: %@", NSStringFromSelector(sel));
}
return 0;
}CSVExporter: a,b,c
JSONExporter: ["a","b","c"]
XMLExporter: not available
selector name: export
Class is the type of a class object. [cls new] creates an instance of whatever class cls refers to.
Test yourself
Bird inherits from Animal. What does [[Bird new] isMemberOfClass:[Animal class]] return?
- YES
- NO
- nil
- It raises an exception
Which method tells you whether an object implements a particular method?
- conformsToProtocol:
- isKindOfClass:
- respondsToSelector:
- hasMethod:
What does NSClassFromString(@"NoSuchClass") return?
- NSObject
- nil
- An empty class
- It crashes