Objective-C: id, accessing instance properties, synthesize?
Asked Answered
D

2

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.

Dismay answered 19/4, 2012 at 12:5 Comment(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.Madame
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.Dismay
B
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";
Banquette answered 19/4, 2012 at 12:12 Comment(2)
Ah thanks, not sure I understand those yet, but I'll have a play with it and see how I get on.Dismay
More information on protocols: developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC/…Banquette
L
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...

Lordosis answered 19/4, 2012 at 12:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.