id 和instancetype的区别
来源:互联网 发布:网络电视怎么搜台 编辑:程序博客网 时间:2024/05/21 19:29
建议以后使用instancetype
a)id表示类型,而instancetype只能用做方法的返回类型
b)id作为构造方法返回实例对象时,在使用时,不会坚持类型是否一致,而instancetype则会检测类型
例:
(1).id的使用
Person的实现:
@implementation Person
+ (id) personWithName:(NSString *)name
{
return [[self alloc] init];//注意这里使用self不要直接用Person
}
@end
Student类是Person类的子类,上面[Student personWithName:@”sdf”]返回的是Student对象,但是main函数中使用了NSString类型的指针来指向Student的对象空间,且调用了length,实际上这块空间中是没有length方法的,所以会出错,即使用id作为返回时,没有检查NSString *str = [Student personWithName:@"sdf"];
这段代码两端的类型,
(2)instancetype的使用
上面使用instancetype后,在程序还没有编译时就会检测下面这段代码:
NSString *str = [Student personWithName:@"sdf"];
a)id表示类型,而instancetype只能用做方法的返回类型
b)id作为构造方法返回实例对象时,在使用时,不会坚持类型是否一致,而instancetype则会检测类型
例:
(1).id的使用
Person的实现:
@implementation Person
+ (id) personWithName:(NSString *)name
{
return [[self alloc] init];//注意这里使用self不要直接用Person
}
@end
Student类是Person类的子类,上面[Student personWithName:@”sdf”]返回的是Student对象,但是main函数中使用了NSString类型的指针来指向Student的对象空间,且调用了length,实际上这块空间中是没有length方法的,所以会出错,即使用id作为返回时,没有检查NSString *str = [Student personWithName:@"sdf"];
这段代码两端的类型,
(2)instancetype的使用
上面使用instancetype后,在程序还没有编译时就会检测下面这段代码:
NSString *str = [Student personWithName:@"sdf"];
0 0
- instancetype和id的区别
- instancetype和id的区别
- instancetype和id的区别
- instancetype 和id的区别
- instancetype 和 id 的区别
- instancetype和id的区别
- id 和 instancetype 的区别
- id 和instancetype的区别
- instancetype和id的区别
- instancetype和id的区别
- instancetype和id的区别
- instancetype和id的区别
- id和instancetype的区别
- instancetype 和 id 的区别
- instancetype和id的区别
- instancetype 和 id 的区别
- instancetype 和 id的区别
- id和instancetype的区别
- 子类对象创建的同时有没有创建父类对象
- 黑马程序员——我理解的设计模式
- java学习帮助文档
- 图的遍历——广度优先遍历——邻接表
- thinkphp学习要点
- id 和instancetype的区别
- linux命令:cat(常用方法详解)
- HTTP中Get与Post的区别
- Atom配置
- JAVA使用脚本引擎执行JS
- 使用AFNetworking POST 中文乱码?
- linux下history命令的使用方法
- OC中的分类Category
- vb.net机房收费系统报表设计