I’m developing an iOS application with CoreData.
I have these two entities:
Shop

Category

I’m trying to access category.name from Shop entity but I get an error:
- (void)updateDetails:(NSManagedObject *)shop
{
NSLog(@"updateDetails: %@", shop);
if (shop == nil)
return;
self.nameLabel.text = [[shop valueForKey:@"name"] description];
self.categoryLabel.text = [[shop valueForKey:@"category.name"] description];
self.addressLabel.text = [[shop valueForKey:@"address"] description];
self.telephoneLabel.text = [[shop valueForKey:@"telephone"] description];
NSNumberFormatter* f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber* acceptRate = [f numberFromString:[[shop valueForKey:@"acceptRate"] description]];
_ratingControl.rating = [acceptRate unsignedIntValue];
}
I retrieve Shop entities this way:
NSManagedObjectContext *context = [self managedObjectContext];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Shop"
inManagedObjectContext:context];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:entity];
NSArray *results = [context executeFetchRequest:fetchRequest error:nil];
But I get this error:
'[<NSManagedObject 0x1cdb4890> valueForUndefinedKey:]: the entity Shop is not key value coding-compliant for the key "category.name".'
How can I solve this error?
self.categoryLabel.text = [[shop valueForKey:@"category.name"] description];should be
self.categoryLabel.text = [[shop valueForKeyPath:@"category.name"] description];Reason: From the Key Value Coding Documentation
A key is a string that identifies a specific property of an object. Typically, a key corresponds to the name of an accessor method or instance variable in the receiving object. Keys must use ASCII encoding, begin with a lowercase letter, and may not contain whitespace.
Some example keys would be
payee,openingBalance,transactionsandamount.A key path is a string of dot separated keys that is used to specify a sequence of object properties to traverse. The property of the first key in the sequence is relative to the receiver, and each subsequent key is evaluated relative to the value of the previous property.
For example, the key path
address.streetwould get the value of the address property from the receiving object, and then determine the street property relative to the address object.