5

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.

2
  • Is it an error, or a compiler warning? It will work at runtime but the reason for the compiler warning is simply that you are using the generic id type to refer to the object; it doesn't know until runtime if the message will be handled by the object or not. If you want to avoid the warning then use the correct class pointer.
    – trojanfoe
    Apr 19, 2012 at 12:13
  • Thanks, it labelled it as a semantic issue, so not sure which that is, but it didn't run in the iphone simulator when I tried it. Apr 19, 2012 at 12:53

2 Answers 2

9

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

Properties need more information respect to simple messages. So the answer is.. you can't call a property on an id object. But you can use messages, casting (if you are not sure, use reflection to find out the object type), protocols...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.