5

I'm crashing with this message :

'NSInvalidArgumentException', reason: 'keypath name not found in entity

Obvisouly I'm not querying my entity correctly .

//fetching Data

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

NSManagedObjectContext *context = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Viewer" inManagedObjectContext:context];
[fetchRequest setEntity:entity];

NSString *attributeName = @"dF";

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@",attributeName];
[fetchRequest setPredicate:predicate];

NSLog(@"predicate : %@",predicate);
NSError *error;
NSArray *items = [context executeFetchRequest:fetchRequest error:&error];
NSLog(@"items : %@",items);

[fetchRequest release];
    
//end of fetch

And here is my data Model:

alt text

I want to return the value of "dF", shouldn't call it like this ? :

NSString *attributeName = @"dF";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name like %@",attributeName];
pkamb
  • 33,281
  • 23
  • 160
  • 191
Finger twist
  • 3,546
  • 9
  • 42
  • 52

2 Answers2

8

If you want to get value from your dF property, you have to fetch an array of NSManagedObjects and then use [fetchedManagedObject valueForKey:@"dF"]; to get your value.

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSManagedObjectContext *context = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Viewer" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *items = [context executeFetchRequest:fetchRequest error:&error];
[fetchRequest release];

NSManagedObject *mo = [items objectAtIndex:0];  // assuming that array is not empty
id value = [mo valueForKey:@"dF"];

Predicates are used to get array of NSManagedObjects that satisfy your criteria. E.g. if your dF is a number, you can create predicate like "dF > 100", then your fetch request will return an array with NSManagedObjects that will have dF values that > 100. But if you want to get just values, you don't need any predicate.

beefon
  • 3,194
  • 1
  • 21
  • 25
0

I was using a NSSortDescriptor initialized with a String key:

let fetchRequest = NSFetchRequest<SomeManagedObject>(entityName: "SomeManagedObject")
let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]

I then changed the name of the name attribute in the model. Refactored all of the property names, but didn't catch the stringly typed key: "name".

The solution for Swift is to use NSSortDescriptor(keyPath: instead, which will fail to compile if the property key path changes.

NSSortDescriptor(keyPath: \SomeManagedObject.firstName, ascending: true)
pkamb
  • 33,281
  • 23
  • 160
  • 191