Naren Naren - 1 year ago 69
Objective-C Question

Setting value of instance variable dynamically

I'm trying to set the value of an instance variable dynamically at runtime in Objective-C.
Assume I have a class called stock which has an instance variable float price.
I have the following code:

stock* s;
...//initialisation etc
float newPrice = 12.56;
Ivar variable = class_getInstanceVariable(NSClassFromString(@"stock"), "price");
float* pricePointer = (float*)((char *)c + ivar_getOffset(variable));
(*pricePointer) = newPrice;
NSLog(@"%f", [s price]);

The last line however always indicates that the price is 0.00 ie. not set.
I do have a property declared on the price. So [s price] should return the price correctly.

Can anyone tell me what I am doing wrong here?


Answer Source

Found the problem. Since the class stock contains the instance variable price as well as the property price, the value of the instance variable was not being set. Rather the value of the property. This is not going to work as property is a method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download