类型转换在IOS从CustomObject到ID
问题描述:
,如果我们强制转换自定义对象到id
会发生什么,类型转换在IOS从CustomObject到ID
我从不兼容型有分配的问题id
Myclass* __Strong
工作代码:
self.delegate=(id)mycustomobject;
然后我键入我的对象到id
,这一切都很好,作为一种魅力工作。
但我的问题是会有任何后来出乎意料的问题。如果是这样,避免此类警告的最佳方法是什么。
答
要回答你的问题的第一部分,如果您分配一个对象id
你的对象将失去在编译时间范围类的关联,这意味着,如果你在你的MyClass
类有一个属性名NSString
型myProp
和你做像
id tempVar = (id)objMyClass;
然后你将无法在编译时访问属性myProp
。
NSString *propValue = tempVar.myProp; // This will throw an error "Property not found".
为了解决为什么你在分配对象,是因为你声明的属性delegate
为id
类型,是符合MyClassProtocol
协议,像
@property (nonatomic,assign) id<MyClassProtocol> delegate;
但是你有没有符合面临的问题到MyClassProtocol
您的班级MyClass
。因此,当您使用id
类型强制转换编写代码时,实际上是将id
类型的对象(委托)分配给MyClass
的对象,这从编译器的角度来看是错误的。
self.delegate = mycustomobject; // Wrong; delegate data type is id while your custom object is of type MyClass
所以,当MyClass
符合协议的self
将成为这符合MyClassProtocol
,并最终将支持id<MyClassProtocol>
这意味着任何数据类型符合该协议的数据类型。