0

I have a function, that recieves an object, a name of a property and its value. Could i set the property of the object with something simple like this:

-(void)dynamicSetterWithProperty:(NSString*)propertyThatIsKnownOnlyInRuntime
                        andValue:(NSString*)valueThatIsKnownOnlyInRuntime{

       _myObject.propertyNameThatIsKnownOnlyInRuntime = valueNameThatIsKnownOnlyInRuntime;

}

Or do I have to do it in this ugly way:

-(void)dynamicSetterWithProperty:(NSString*)propertyThatIsKnownOnlyInRuntime
                        andValue:(NSString*)valueThatIsKnownOnlyInRuntime{

       if([propertyNameThatIsKnownOnlyInRuntime isEqualToString@"name"]){
              _myObject.name = valueNameThatIsKnownOnlyInRuntime;
       }

       else if([propertyNameThatIsKnownOnlyInRuntime isEqualToString@"age"]){
              _myObject.age = valueNameThatIsKnownOnlyInRuntime;
       }

}
Luda
  • 7,282
  • 12
  • 79
  • 139
  • @KurtRevis This what I get for setValue:forKey [ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key 1759. האם אוטובוס – Luda Jun 29 '13 at 22:11

1 Answers1

3

Well, you can utilize KVC:

[_myObject setValue:runtimeValue forKey:runtimeProperty];

of course you could check first if the property is valid with respondsToSelector or catch any invalid messages by overriding valueForUndefinedKey: and setValue:forUndefinedKey: in your subclass.

Alladinian
  • 34,483
  • 6
  • 89
  • 91
  • Technically, you can't in the general case use `respondsToSelector:` to tell whether an object is KVC-compliant for a key, because accessors don't need to follow a set scheme with declared properties. I think it's usually best just to go ahead and let the operation fail naturally unless there is some strong local reason to prevent it. – Chuck Jun 29 '13 at 22:04
  • This is what I get: [ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key 1759. האם אוטובוס – Luda Jun 29 '13 at 22:10
  • Well this means that `QuestionDetails` doesn't have a `1759` property. @Chuck True, thanks for pointing that out. – Alladinian Jun 29 '13 at 22:13