zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

iOS使用instancetype类型

ios 类型 使用
2023-09-11 14:14:25 时间

instancetype是clang 3.5开始提供的一个关键字,跟id类似,用于表示某个方法返回的未知类型的Objective-C对象,苹果在iOS 8中全面使用instancetype代替id。

instancetype和id的区别:

以下面代码为例

@interface MyObject : NSObject
+ (instancetype)methodA;
+ (id)methodB;

@end

@implementation MyObject

+ (instancetype)methodA
{
    return [[[self class] alloc] init];
}

+ (id)methodB
{
    return [[[self class] alloc] init];
}

@end

调用定义的方法methodA和methodB

x = [[MyObject methodA] count];
y = [[MyObject methodB] count];

因为instancetype具有对象类型检测功能,因此methodA函数的返回对象类型就是MyObject,而MyObject是没有count这个函数的,所以编译器会在x行这里提示警告"’MyObject’ may not respond to ‘count’"

而id类型不具备类型检测功能,其泛指所有class,而count函数有可能存在任何一个class中(比如NSArray),所以y对应的代码不会警告,不过在真正运行到此处代码时,程序就会crash

注意事项

(1)instancetype只能作为函数返回值,不能用来定义定义变量。

(2)用instancetype作为函数返回值返回的是函数所在类的类型。

 

如果想让方法在继承的子类中仍能返回对应的类型,使用[self class]而不是[类名 alloc]的方式。

+ (instancetype)methodA
{
    return [[[self class] alloc] init];
}