Regan
Regan

Reputation: 1497

Incorporate two attributes in cocoa bindings

Say I have a Core Data Entity called Person, with the attributes firstName and lastName.

I want to display that person's full name, or firstName + lastName, in a tableView, which updates whenever either firstName or lastName is updated in typical cocoa bindings fashion.

What would I need to bind to make that work? I was thinking of binding to a method that just returns the formatted string based on those two attributes, and then figuring out some way to trigger an update of that method if either of the two that it is dependent on are updated, but wasn't sure quite how/where that would happen.

Upvotes: 0

Views: 49

Answers (1)

stevesliva
stevesliva

Reputation: 5655

You want to create a getter called fullName and register dependent keyPaths for it.

Incidentally the code there is exactly what you want.

- (NSString*) fullName
{
  return [NSString stringWithFormat:@"%@ %@",firstName,lastName];
} 

+ (NSSet *)keyPathsForValuesAffectingFullName {
    return [NSSet setWithObjects:@"lastName", @"firstName", nil];
}

Whenever firstName or lastName is updated, KVO observers of fullName are notified that the value changed. That includes items bound to fullName.

You can do quite fancy things with this pattern, like have changes in an object graph trigger recalculation of properties describing the object graph. There's a little trick in there where I call an empty setter from a child class to force a recalculation of a relationship that's dependent on the parent's to-many children keyPath. This avoids Apple's suggested (and painful) pattern of registering KVO observers. As long as you own the code in the dependent keypaths in the child classes, you can have the child's instance methods simply call a dependent property on the parent class that triggers a call to the getter that uses the dependent on keypaths in the child. So avoid in practice what Apple suggests with having the parent class maintain a huge painful morass of code that registers as a KVO observer of each child.

Upvotes: 1

Related Questions