强制转换为 (id) 以保证属性存在

发布于 2024-10-08 18:26:03 字数 452 浏览 1 评论 0原文

如果我有许多类似的类

@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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

踏月而来 2024-10-15 18:26:03

在这种情况下,我更喜欢消息发送符号而不是点符号,因为它清楚地显示了何时发生转换:

这些行是相等的:

[(id<MyProtocol>)anObject myString]
((id<MyProtocol>)anObject).myString

这些是:

(id<MyProtocol>)[anObject myString]
(id<MyProtocol>)anObject.myString

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:

[(id<MyProtocol>)anObject myString]
((id<MyProtocol>)anObject).myString

And these are:

(id<MyProtocol>)[anObject myString]
(id<MyProtocol>)anObject.myString
记忆里有你的影子 2024-10-15 18:26:03

忽略这个..结果只是需要更多括号:

((id<myProtocol>)anObject).myString

ignore this.. turns out just to need more brackets:

((id<myProtocol>)anObject).myString
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文