ajrlewis
ajrlewis

Reputation: 3058

Objective C: when valueForKey is an instance with properties

i am trying to extract a property of an instance of a class that is a property of another class! easier shown by example...

// Person is a class with properties: name and age
Person *person = [[Person alloc] init];
[person setName:@"Alex"];

// Age is a class with properties value (i.e. 100) and unit (i.e. year)
Age *age = [[Age alloc] init];
[age setValue:@100];
[person setAge:age];

NSMutableArray *people = [[NSMutableArray alloc] init];
[people addObject:person];

for (id person in people) {

how can i extract the value property of the age instance associated to the person?

    //[person valueForKey:@"age.value")];

i expect to get @100 - i get 'NSInvalidArgumentException'

this gives me the instance of Age - but i would rather have the value property.

    //[person valueForKey:@"age")];
}

is this possible? any help is much appreciated.

Upvotes: 0

Views: 167

Answers (2)

vadian
vadian

Reputation: 285059

you want to get value of age of person. I changed the code to dot.notation, it's just person.age.value

 Person *person = [[Person alloc] init];
  person.name = @"Alex";

  // Age is a class with properties value (i.e. 100) and unit (i.e. year)
  Age *age = [[Age alloc] init];
  age.value = @100;
  person.age = age;

  NSMutableArray *people = [[NSMutableArray alloc] init];
  [people addObject:person];

  for (id person in people) {
    person.age.value
  }

Upvotes: 0

Tommy
Tommy

Reputation: 100612

Use valueForKeyPath: rather than valueForKey: to handle [potential] traversal of an object graph rather than mere top-level look up.

[person valueForKeyPath:"age.value"] should be correct.

Upvotes: 2

Related Questions