usrgnxc
usrgnxc

Reputation: 804

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 doesn't this work? i still get the same error.

Upvotes: 15

Views: 6962

Answers (2)

vikingosegundo
vikingosegundo

Reputation: 52237

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

Upvotes: 30

usrgnxc
usrgnxc

Reputation: 804

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

((id<myProtocol>)anObject).myString

Upvotes: 6

Related Questions