杂记 id和instancetype的区别

223 阅读1分钟

1.Using instancetype instead of id in appropriate places improves type safety in your Objective-C code

@interface MyObject : NSObject
+ (instancetype)factoryMethodA;
+ (id)factoryMethodB;
@end
 
@implementation MyObject
+ (instancetype)factoryMethodA { return [[[self class] alloc] init]; }
+ (id)factoryMethodB { return [[[self class] alloc] init]; }
@end
 
void doSomething() {
    NSUInteger x, y;
 
    x = [[MyObject factoryMethodA] count]; // Return type of +factoryMethodA is taken to be "MyObject *"
    y = [[MyObject factoryMethodB] count]; // Return type of +factoryMethodB is "id"
}

Because of the instancetype return type of +factoryMethodA, the type of that message expression is MyObject *. Since MyObject doesn’t have a -count method, the compiler gives a warning about the x line:

main.m: ’MyObject’ may not respond to ‘count’ However, because of the id return type in +factoryMethodB, the compiler can give no warning about the y line. Since an object of type id can be any class, and since a metho