Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: id, accessing instance properties, synthesize?

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.

like image 892
WilliamAmateur Avatar asked Apr 19 '12 12:04

WilliamAmateur


1 Answers

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:

Declaring a new variable

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";

Casting

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";

Protocols

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";
like image 82
jtbandes Avatar answered Oct 03 '22 12:10

jtbandes