强制转换为 (id) 以保证属性存在
如果我有许多类似的类
@property (nonatomic, retain) NSString* myString;
,并且想要访问属于这些类之一的对象中的该属性(但不知道是哪个,所以它是类型 id),我显然会得到“请求成员‘myString’不是结构或联合的东西”错误。
因此,如果每个类都符合:
@protocol myProtocol <NSObject>
@required
@property (nonatomic, retain) NSString* myString;
@end
然后我像这样进行转换以获得属性:
(id<myProtocol>)anObject.myString
为什么这不起作用?我仍然遇到同样的错误。
if i have a number of classes with something like
@property (nonatomic, retain) NSString* myString;
and want to access that property in a object that is one of these classes (but don't know which so it is type id), i obviously get "request for member 'myString' in something not a structure or union" error.
so if each of these classes conforms to :
@protocol myProtocol <NSObject>
@required
@property (nonatomic, retain) NSString* myString;
@end
then i cast like this to get the property:
(id<myProtocol>)anObject.myString
why doesn't this work? i still get the same error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这种情况下,我更喜欢消息发送符号而不是点符号,因为它清楚地显示了何时发生转换:
这些行是相等的:
这些是:
In this case I prefer the messages-sending notation over the dot-notation, as it shows clearly, when the cast will happen:
These lines are equal:
And these are:
忽略这个..结果只是需要更多括号:
ignore this.. turns out just to need more brackets: