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];
}
相关文章
- 判断不同IOS设备
- iOS 设备类型和版本判断
- [iOS]iOS AudioSession详解 Category选择 听筒扬声器切换
- iOS开发UI篇—ios应用数据存储方式(归档)
- iOS开发UI篇—ios应用数据存储方式(偏好设置)
- iOS开发UI篇—ios应用数据存储方式(XML属性列表-plist)
- iOS中 蓝牙2.0详解/ios蓝牙设备详解
- xcode ios 怎么导入p12证书
- iOS swift5 值类型和引用类型
- iOS swift present出UINavigationController然后present
- iOS oc 扩展(Extension)
- cordova调用ios原生(js调用swift)
- nginx与ios实现https双向认证
- iOS依据字符串计算UITextView高度
- 字节跳动iOS客户端实习岗位面试问题