2
votes

So far all the examples I can find are direct binding between Core Data and NSArrayController. That means each NSArrayController maps exactly one entity.

Is there a way to customize what's get populated into the NSArrayController?

For example, I have two entities:

FileMetaData
    ID
    FileName
    FileSize
    Owner(relationship m..1 to SystemUser)

SystemUser
    ID
    FirstName
    LastName
    Files(relationship 1..m to FileMetaData)

I have one NSArrayController to populate a tableview that has two column, one is "FileName", and the other one is "UserName". UserName comes from FirstName + Lastname in SystemUser entity. The NSArrayController is set to bind with FileMetaData.

What is the best way to do this? Thanks.

2

2 Answers

1
votes

One way to easily get a UserName property (FirstName + LastName) is to define a category on the SystemUser class with a UserName method that returns the FirstName and LastName properties duly concatenated.

Then in your various bindings you can bind to the UserName property. Typed directly into the browser, so not tested, a UISupport (or any other name) category SystemUser could look like this:

// In SystemUser+UISupport.m

- (NSString *)userName
{
    return [NSString stringWithFormat: @"%@ %@", self.FirstName, self.LastName];
}

In order for the bindings to work if the FirstName or LastName properties change, you might want to implement this method, too:

+(NSSet*)keyPathsForValuesAffectingUserName
{
    return [NSSet setWithObjects: @"self.FirstName", @"self.LastName", nil];
}

Finally, for completeness, you can declare your new-fangled read-only property in the header file:

// In SystemUser+UISupport.h

@property (readonly) NSString *userName;
0
votes

I think Monolo's solution is better than mine, but just for an alternative, I will post my solution as well.

My approach is to add a new "displayName" field in SystemUser.m. And implement NSManagedObject's willSave() method.

-(void)willSave
{
    if (self.displayName == nil)
    {
        self.displayName = [NSString stringWithFormat:@"%@ %@", self.firstName, self.lastName];
    }
}

This way the displayName field gets updated before CoreData attempts to save the entity.