开发者

casting to (id<protocol>) to guarantee a property is there

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 d开发者_开发技巧oesn't this work? i still get the same error.


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


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

((id<myProtocol>)anObject).myString
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜