1
- (NSManagedObjectContext *)anObjectByEntityForName:(NSString *)entityName withValue:(NSObject *)value forKeyPath:(NSString *)keyPath {
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:entityName inManagedObjectContext:self.managedObjectContext]];
[request setPredicate:[NSPredicate predicateWithFormat:@"%@ == %@", keyPath, value]];

NSError *error = nil;
NSMutableArray *mutableFetchResults = [[self.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (!mutableFetchResults) {
    [request release];
    [mutableFetchResults release];
    return nil;
}

if ([mutableFetchResults count] == 0) {
    [request release];
    [mutableFetchResults release];
    return nil;
}

id anObject = [mutableFetchResults objectAtIndex:0];
[request release];
[mutableFetchResults release];

return anObject;
}

This code returns nil, for a keypath "isSelected" and value @YES. But in case there is no predicate, then all the objects are returned. In the database there are minimum 1 object that meets the criteria. What can be wrong with whit?

Infinite Possibilities
  • 7,415
  • 13
  • 55
  • 118

1 Answers1

4

For keys or key paths, you have to use the %K format:

[request setPredicate:[NSPredicate predicateWithFormat:@"%K == %@", keyPath, value]];

Shown in the Documentation

bvogelzang
  • 1,405
  • 14
  • 17
  • Wow, that was so easy... Do you have any documentation for this on apple docs? – Infinite Possibilities Apr 01 '13 at 23:22
  • 1
    Updated answer to include documentation link: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/Articles/pSyntax.html#//apple_ref/doc/uid/TP40001795-SW2 – bvogelzang Apr 01 '13 at 23:24