iOS instancetype or id ?
2015-12-15 10:15
363 查看
The id type simply says a method will return a reference to an object. It could be any object of any type.
The instancetype type says a method will return a reference to an object of the same type as the class on which this method was called.
instancetype is a newer feature of Objective-C that basically adds type safety. In many cases, you will see no difference in an app (as you have mentioned). But there are times when instancetype is useful to avoid having to type cast when you call the method.
For example, imagine a class called SomeClass with a method like this:
Then imagine a subclass of SomeClass called SomeSubclass, that overrides that method like this:
Now, if you want to create a SomeSubclass, you would have to do this:
However, if createSomeClass returned instancetype instead of id, then you could write this instead:
You will see many people switching to instancetype for return values from any initializer or class creator methods (like the ones shown above). In fact, many of Apple's own APIs have been changed to use instancetype instead of id.
From: http://raywenderlich.com/forums/viewtopic.php?f=38&t=8959 , thanks !
The instancetype type says a method will return a reference to an object of the same type as the class on which this method was called.
instancetype is a newer feature of Objective-C that basically adds type safety. In many cases, you will see no difference in an app (as you have mentioned). But there are times when instancetype is useful to avoid having to type cast when you call the method.
For example, imagine a class called SomeClass with a method like this:
+(id)createSomeClass { return [[SomeClass alloc] init]; }
Then imagine a subclass of SomeClass called SomeSubclass, that overrides that method like this:
+(id)createSomeClass { return [[SomeSubclass alloc] init]; }
Now, if you want to create a SomeSubclass, you would have to do this:
SomeSubclass *obj = (SomeSubclass*)[SomeSubclass createSomeClass];
However, if createSomeClass returned instancetype instead of id, then you could write this instead:
SomeSubclass *obj = [SomeSubclass createSomeClass];
You will see many people switching to instancetype for return values from any initializer or class creator methods (like the ones shown above). In fact, many of Apple's own APIs have been changed to use instancetype instead of id.
From: http://raywenderlich.com/forums/viewtopic.php?f=38&t=8959 , thanks !
相关文章推荐
- 为什么安卓没有IOS流畅?看完你就明白了
- iOS自带图片大小压缩
- ios怎么让状态栏颜色和导航栏背景图片颜色一样
- iOS之NSDate
- 【收藏】众多iOS开源资源库
- 生产环境开源监控系统整合Nagios+Cacti+Nconf
- 在IOS上捕获视频
- iOS方法类:CGAffineTransform
- iOS 坐标转换
- IOS导航栏颜色渐变与常用属性
- iOS 实现类似安卓.9.png图片拉伸效果
- [iOS运行错误系列-001]
- phonegap(cordova) 入门 6----iOS 扫码插件,好用,方便,效率高,漂亮,兼容二维码,条形码
- ios知识总结
- IOS中在自定义控件(非视图控制器)的视图跳转中 代理方法与代码块的比较
- iOS-SDWebImage
- iOS-Block
- iOS-推送通知详解
- iOS-推送,证书申请,本地推送
- iOS-远程推送