Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 341
jonydep Avatar asked Dec 21 '10 10:12

jonydep


People also ask

What's the difference between a protocol and a class in Swift?

You can create objects from classes, whereas protocols are just type definitions. Try to think of protocols as being abstract definitions, whereas classes and structs are real things you can create.

What is protocol in Objective C with example?

Objective-C allows you to define protocols, which declare the methods expected to be used for a particular situation. This chapter describes the syntax to define a formal protocol, and explains how to mark a class interface as conforming to a protocol, which means that the class must implement the required methods.

How do you call a delegate method in Objective C?

To create one, you define a class that implements the delegate methods you're interested in, and mark that class as implementing the delegate protocol. Then you could create an instance of MyClass and assign it as the web view's delegate: MyClass *instanceOfMyClass = [[MyClass alloc] init]; myWebView.


2 Answers

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
like image 120
vikingosegundo Avatar answered Nov 16 '22 02:11

vikingosegundo


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

((id<myProtocol>)anObject).myString
like image 21
jonydep Avatar answered Nov 16 '22 04:11

jonydep