Search code examples
iphoneobjective-cpyobjc

How can I set an instance variable dynamically?


I can set a instance variable via a @property using:

SEL s = NSSelectorFromString([NSString stringWithFormat:@"set%@:", property]);
[self performSelector: s withObject: newObject];

but is there a way to set an instance variable directly and dynamically ?


Solution

  • It's not quite as efficient as using a selector directly, but you can use -[setValue:forKey:] to set properties dynamically. So, if you have a property named foo and you want to set it to @"bar", you would do:

    [self setValue:@"bar" forKey:@"foo"];
    

    Just remember, since this only takes object references, you have to properly box any primitives. So, if you have a property called foobar that takes an NSInteger value, you would do:

    [self setValue:[NSNumber numberWithInteger:5] forKey:@"foobar"];