I'm very new to Objective-C, I'm wondering if there is a simple way to set an id to be an object instance (which has synthesized properties), and directly get/set those properties like:
id myID = myInstance;
myID.myProperty = something;
Where myInstance is an object with a synthesized property called myProperty. When I just do:
myInstance.myProperty = something;
It works, but when I've switched it for an id I get the error
Property 'myProperty' not found on object of type '_strong id'
Do I have to manually make getter/setter methods instead of using synthesize when using an id? Because I do seem to be able to make the id perform the instances methods.
If the object must be of type id
, you can use messages (rather than dot notation) to access getters/setters:
id myID = ...;
NSString *prop = [myID property];
[myID setProperty:@"new value"];
But you have better alternatives:
If you know the object's class, just make a variable with that type.
id myID; // defined elsewhere
MyClass *obj = (MyClass *)myID; // if you know the class, make a variable with that type
obj.property = @"new value";
Use an inline cast to tell the compiler what the type is without making a new variable.
id myID; // defined elsewhere
((MyClass *)myID).property = @"new value";
If you don't know the exact class of the object but you know that it must implement certain methods, you can create a protocol:
id<MyProtocol> myID; // the compiler knows the object implements MyProtocol
myID.property = @"new value";
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