0

I have properties firstName and lastName in NSManagedObject class. I need another property uppercaseFirstLetter which is calculated from these two. Property uppercaseFirstLetter can't be transient and it will be using for sectionNamedKeyPath

[[NSFetchedResultsController alloc] initWithFetchRequest: fetchRequest 
                                    managedObjectContext: [DatabaseManager context]
                                      sectionNameKeyPath: @"uppercaseFirstLetter" 
                                               cacheName: nil];   

and for sort descriptor

NSSortDescriptor *sortLastNameDescriptor = 
[[NSSortDescriptor alloc] initWithKey: @"uppercaseFirstLetter" 
                            ascending: YES 
                             selector: @selector(localizedStandardCompare:)]; 

This is code for calculating uppercaseFirstLetter:

NSString *aString = nil;
NSString *lastName = [self valueForKey:@"firstName"];
NSString *firstName = [self valueForKey:@"lastName"];

if (lastName.length) {
    aString = [lastName uppercaseString];
} else if (firstName.length) {
    aString = [firstName uppercaseString];
} else {
    aString = @"#";
}

NSString *stringToReturn = [aString substringToIndex:1];

How i need to create uppercaseFirstLetter and what changes in code should do to attain this result?

Andrey Banshchikov
  • 1,558
  • 2
  • 15
  • 27
  • Did you look at adding a custom setter method? Or what other methods on `NSManagedObject` could help? – Wain Mar 04 '14 at 11:27
  • 1
    Related: http://stackoverflow.com/questions/4874193/core-data-willsave-method – Wain Mar 04 '14 at 11:31

1 Answers1

1

You can use custom setter methods for firstName and lastName to update the uppercaseFirstLetter property:

- (void)setFirstName:(NSString *)firstName
{
    [self willChangeValueForKey:@"firstName"];
    [self setPrimitiveValue:firstName forKey:@"firstName"];
    [self updateUppercaseFirstLetter];
    [self didChangeValueForKey:@"firstName"];
}

You also have to do this for lastName.

Or you observe changes for firstName and lastName via KVO to update uppercaseFirstLetter if needed. There are many solutions out there how to solve this. Keywords: "NSManagedObject" "KVO"

The last solution might be the more elegant way.

Florian Mielke
  • 3,310
  • 27
  • 31