iOS - id与NSObject*与id<NSObjec

2018-01-12  本文已影响172人  SkyMing一C
图片源于网络

id:

typedef struct objc_class *Class;
typedef struct objc_object {
    Class isa;
} *id;

NSObject *:

id<NSObject>

@interface NSObject <NSObject> {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-interface-ivars"
    Class isa  OBJC_ISA_AVAILABILITY;
#pragma clang diagnostic pop
}
@interface NSProxy <NSObject> {
    Class   isa;
}

instancetype

@interface NSArray  
+ (id)constructAnArray;  
+ (instancetype)constructAnArray1;  
@end 

[NSArray constructAnArray];  
//根据Cocoa的方法命名规范,得到的返回类型就和方法声明的返回类型一样,是id。
[NSArray constructAnArray1]; 
//根据Cocoa的方法命名规范,得到的返回类型和方法所在类的类型相同,是NSArray*!
In your code, replace occurrences of id as a return value with instancetype where appropriate. This is typically the case for init methods and class factory methods. Even though the compiler automatically converts methods that begin with “alloc,” “init,” or “new” and have a return type of id to return instancetype, it doesn’t convert other methods. Objective-C convention is to write instancetype explicitly for all methods.

参考

id、NSObject *、id<NSObject>、instancetype的区别

iOS中id - NSObject* - id<NSObject>的区别

上一篇下一篇

猜你喜欢

热点阅读