Search code examples
iphoneobjective-cipadcore-datansfetchrequest

Fetching an Integer From CoreData?


I have fetched a result from core data in my app and need to get the integer value of its 'capacity' attribute I gave it.

The 'capacity' attribute is an NSInteger 16 in my core data model.

I get my result like so:

entity = [NSEntityDescription entityForName:@"TableInfo" inManagedObjectContext:appDelegate.managedObjectContext];
    [fetchRequest setEntity:entity];
    [fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"name == %@", [NSString stringWithFormat:@"%@", [tablesArray objectAtIndex:row]]]];

    NSArray *selectedTableFetched = [appDelegate.managedObjectContext executeFetchRequest:fetchRequest error:&error];

Now my problem is how do I get the 'capacity' value from my result? I know there is a result as I have check the count of the array and I have tried this:

NSNumber *n = [selectedTableFetched valueForKey:@"capacity"];

It gives me something, when accessing the NSNumber I get a meaningless long number, so if I try and access the integer value like so:

[n integerValue]

it crashes the app and I get this error:

'NSInvalidArgumentException', reason: '-[__NSArrayI integerValue]: unrecognized selector sent to instance 0x138870'

All I need to do is get that integer value from the capacity attribute.


Solution

  • selectedTableFetched is an array:

    NSArray *selectedTableFetched = [appDelegate.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    

    So you want to work with an element (presumably the only element, based on your fetchRequest's predicate) before you do valueForKey:

    NSManagedObject *managedObject = [selectedTableFetched lastObject];
    NSNumber *n = [managedObject valueForKey:@"capacity"];
    NSInteger *yourInteger = [n integerValue];