Objective-C在C ++ 11中是不是像auto一样?

时间:2014-03-23 17:07:49

标签: objective-c c++11 types

在像

这样的代码中
- (void)driveFromOrigin:(id)theOrigin toDestination:(id)theDestination;
- (id)initWithModel:(NSString *)aModel;

id允许我指定类型吗?

3 个答案:

答案 0 :(得分:2)

id类似于" void *"。它意味着"指向任何类型的Objective-C实例"。因此,与void *不同,它受ARC控制。它可以分配给任何类型的变量"指向Objective-C对象的指针"反之亦然。

使用" id"类型的变量有一个缺点,编译器不知道你有什么样的对象,所以它允许你向它发送消息,即使它不理解它们。

NSString* aString = @"Hello";
NSUInteger count = aString.count; // Doesn't compile because the compiler knows it's wrong
id bString = aString; // It's a string, but the compiler doesn't know. 
count = bString.count; // Compiles but throws exception at runtime. 

"自动"在C ++中是不同的。它从右侧的参数中确定正确的类型。所以变量是完全声明的,除了编译器提供的类型而不是你。

PS。 "初始化"方法应该返回" instancetype"而不是身份证明。 " instancetype"有点粗略地类似于" auto"。

答案 1 :(得分:1)

是的,在xcode8中,您可以使用__auto_type

答案 2 :(得分:0)

不完全正确。 id表示objective-c对象类型。编译器在compilatrion期间不会知道它的类型。 auto指示编译器推理变量类型。