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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With