Objective-C中的instancetype和id区别
有一个相同两个不同。相同
Written by Mattt Thompson on Dec 10th, 2012
Objective-C is a rapidly evolving language, in a way that you just don't see in established programming languages. ARC, object literals, subscripting, blocks: in the span of just three years, so much of how we program in Objective-C has been changed (for the better).
All of this innovation is a result of Apple's philosophy of vertical integration. Just as Apple's investment in designing its own chipsets gave them leverage to compete aggressively with their mobile hardware, so too has their investment in LLVM allowed their software to keep pace.
Clang developments range from the mundane to paradigm-changing, but telling the difference takes practice. Because we're talking about low-level language features, it's difficult to understand what implications they may have higher up with API design.
One such example is instancetype, the subject of this week's article.
In Objective-C, conventions aren't just a matter of coding best-practices, they are implicit instructions to the compiler.
For example, alloc and init both have return types of id, yet in Xcode, the compiler makes all of the correct type checks. How is this possible?
In Cocoa, there is a convention that methods with names like alloc, or init always return objects that are an instance of the receiver class. These methods are said to have a related result type.
Class constructor methods, although they similarly return id, don't get the same type-checking benefit, because they don't follow that naming convention.
You can try this out for yourself:
[[[NSArray alloc] init] mediaPlaybackAllowsAirPlay]; // ❗ "No visible @interface for `NSArray` declares the selector `mediaPlaybackAllowsAirPlay`"
[[NSArray array] mediaPlaybackAllowsAirPlay]; // (No error)
Because alloc and init follow the naming convention for being a related result type, the correct type check against NSArray is performed. However, the equivalent class constructor array does not follow that convention, and is interpreted as id.
id is useful for opting-out of type safety, but losing it when you do want it sucks.
The alternative, of explicitly declaring the return type ((NSArray *) in the previous example) is a slight improvement, but is annoying to write, and doesn't play nicely with subclasses.
This is where the compiler steps in to resolve this timeless edge case to the Objective-C type system:
instancetype is a contextual keyword that can be used as a result type to signal that a method returns a related result type. For example:
@interface Person
+ (instancetype)personWithName:(NSString *)name;
@end
instancetype, unlikeid, can only be used as the result type in a method declaration.
With instancetype, the compiler will correctly infer that the result of +personWithName: is an instance of a Person.
Look for class constructors in Foundation to start using instancetype in the near future. New APIs, such as UICollectionViewLayoutAttributes are using instancetype already.
下面的翻译:原文地址:http://blog.csdn.net/wzzvictory/article/details/16994913
一、什么是instancetype
instancetype是clang 3.5开始,clang提供的一个关键字,表示某个方法返回的未知类型的Objective-C对象。我们都知道未知类型的的对象可以用id关键字表示,那为什么还会再有一个instancetype呢?
二、关联返回类型(related result types)
根据Cocoa的命名规则,满足下述规则的方法:
1、类方法中,以alloc或new开头
2、实例方法中,以autorelease,init,retain或self开头
会返回一个方法所在类类型的对象,这些方法就被称为是关联返回类型的方法。换句话说,这些方法的返回结果以方法所在的类为类型,说的有点绕口,请看下面的例子:
- @interface NSObject
- + (id)alloc;
- - (id)init;
- @end
- @interface NSArray : NSObject
- @end
当我们使用如下方式初始化NSArray时:
- NSArray *array = [[NSArray alloc] init];
按照Cocoa的命名规则,语句[NSArray alloc] 的类型就是NSArray*因为alloc的返回类型属于关联返回类型。同样,[[NSArray alloc]init] 的返回结果也是NSArray*。
三、instancetype作用
1、作用
如果一个不是关联返回类型的方法,如下:
- @interface NSArray
- + (id)constructAnArray;
- @end
当我们使用如下方式初始化NSArray时:
- [NSArray constructAnArray];
根据Cocoa的方法命名规范,得到的返回类型就和方法声明的返回类型一样,是id。
但是如果使用instancetype作为返回类型,如下:
- @interface NSArray
- + (instancetype)constructAnArray;
- @end
当使用相同方式初始化NSArray时:
- [NSArray constructAnArray];
得到的返回类型和方法所在类的类型相同,是NSArray*!
总结一下,instancetype的作用,就是使那些非关联返回类型的方法返回所在类的类型!
2、好处
能够确定对象的类型,能够帮助编译器更好的为我们定位代码书写问题,比如:
- [[[NSArray alloc] init] mediaPlaybackAllowsAirPlay]; // "No visible @interface for `NSArray` declares the selector `mediaPlaybackAllowsAirPlay`"
- [[NSArray array] mediaPlaybackAllowsAirPlay]; // (No error)
上例中第一行代码,由于[[NSArray alloc]init]的结果是NSArray*,这样编译器就能够根据返回的数据类型检测出NSArray是否实现mediaPlaybackAllowsAirPlay方法。有利于开发者在编译阶段发现错误。
第二行代码,由于array不属于关联返回类型方法,[NSArray array]返回的是id类型,编译器不知道id类型的对象是否实现了mediaPlaybackAllowsAirPlay方法,也就不能够替开发者及时发现错误。
四、instancetype和id的异同
1、相同点
都可以作为方法的返回类型
2、不同点
①instancetype可以返回和方法所在类相同类型的对象,id只能返回未知类型的对象;
②instancetype只能作为返回值,不能像id那样作为参数,比如下面的写法:
- //err,expected a type
- - (void)setValue:(instancetype)value
- {
- //do something
- }
就是错的,应该写成:
- - (void)setValue:(id)value
- {
- //do something
- }
Objective-C中的instancetype和id区别的更多相关文章
- (转)Objective-C中的instancetype和id区别
有一个相同两个不同.相同 Written by Mattt Thompson on Dec 10th, Objective-C is a rapidly evolving language, in a ...
- 转载:Objective-C中的 instancetype 和 id 关键字
Objective-C中的instancetype和id关键字 作者:wangzz 原文地址:http://blog.csdn.net/wzzvictory/article/details/16994 ...
- Objective-C中的instancetype和id关键字(转)
转自:Objective-C中的instancetype和id关键字 一.什么是instancetype 同id一样,都是表示未知类型的的对象. 二.关联返回类型(related result typ ...
- Objective-C中的instancetype与id的区别
一.什么是instancetype instancetype是clang 3.5开始,clang提供的一个关键字,表示某个方法返回的未知类型的Objective-C对象.我们都知道未知类型的的对象可以 ...
- CSS中的class与id区别及用法
转自http://www.divcss5.com/rumen/r3.shtml及http://www.jb51.net/css/35927.html 我们平常在用DIV CSS制作Xhtml网页页面时 ...
- 【转】Objective-C中的instancetype和id关键字
原文:http://blog.csdn.net/wzzvictory/article/details/16994913 一.什么是instancetype instancetype是clang 3.5 ...
- Objective-C中的instancetype和id…
作者:韩俊强 原文地址:http://control.blog.sina.com.cn/admin/article/article_add.php 转载请注明出处 一.什么是instancetype ...
- Objective C中nil/Nil/NULL的区别
nil:指向oc中对象的空指针 Nil:指向oc中类的空指针 NULL:指向其他类型的空指针,如一个c类型的内存指针 NSNull:在集合对象中,表示空值的对象 若obj为nil:[obj messa ...
- ios instancetype与id区别
我们都知道未知类型的的对象可以用id关键字表示,那为什么还会再有一个instancetype呢? instancetype能返回相关联的类型(使那些非关联返回类型的方法返回所在类的类型):而id 返回 ...
随机推荐
- 第一章 : javaScript框架分类及主要功能
从内部架构和理念划分,目前JavaScript框架可以划分为5类. 第一种是以命名空间为导向的类库或框架,如果创建一个数组用new Array(),生成一个对象用new Object(),完全的j ...
- js 选项卡实现
<head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8&quo ...
- "use strict"
"use strict";//严格模式 <!doctype html> <html> <head> <meta charset=" ...
- BZOJ2302 [HAOI2011]Problem c
Description 给n个人安排座位,先给每个人一个1~n的编号,设第i个人的编号为ai(不同人的编号可以相同),接着从第一个人开始,大家依次入座,第i个人来了以后尝试坐到ai,如果ai被占据了, ...
- codevs3031 最富有的人
题目描述 Description 在你的面前有n堆金子,你只能取走其中的两堆,且总价值为这两堆金子的xor值,你想成为最富有的人,你就要有所选择. 输入描述 Input Description 第一行 ...
- JSP登录验证并显示信息
加入C标签: 加入jstl.jar 和standard.jar加入Lib文件夹中 将c.tld放入WEB-Info文件夹中 index.jsp <%@ page language="j ...
- jmap命令详解
1.命令基本概述 Jmap是一个可以输出所有内存中对象的工具,甚至可以将VM 中的heap,以二进制输出成文本.打印出某个java进程(使用pid)内存内的,所有‘对象’的情况(如:产生那些对象,及其 ...
- Java统计数据库表中记录数
public static int count(String txyl_table) {// 获取用户数量 int i = 0;// Store_Information Connection con ...
- UIGestureRecognizer ios手势识别温习
1.UIGestureRecognizer介绍 手势识别在iOS上非常重要,手势操作移动设备的重要特征,极大的增加了移动设备使用便捷性. iOS系统在3.2以后,为方便开发这使用一些常用的手势,提供了 ...
- ios7开发学习笔记-包括c oc 和ios介绍
请查看我的新浪资料分享 http://iask.sina.com.cn/u/2430843520