views:

628

answers:

2

I am just starting out with Core Data and ran into an issue where I need to save the new object with the appropriate ID.

I'm trying to add the next number in the row as an ID for the object the user adds:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Favorites" inManagedObjectContext:managedObjectContext]];
[request setIncludesSubentities:NO];
NSError *err;
NSUInteger count = [managedObjectContext countForFetchRequest:request error:&err];

NSManagedObjectContext *context = [fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[fetchedResultsController fetchRequest] entity];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];

[newManagedObject setValue:[NSNumber numberWithInt:count] forKey:@"favoritesID"];

If I then go and get the valueForKey:@"favoriteID" I get something like "81933072", which is wrong.

I have checked count and it's the correct number, it's just when I put it into Core Data that it becomes something else. favoriteID is an int16 btw.

A: 

Post the code for when you're reading this value.

Steven Canfield
[NSString stringWithFormat:@"%d", [managedObject valueForKey:@"favoriteID"]];
Canada Dev
+4  A: 

valueForKey: will return the NSNumber, not an integer. You need to call [myNumber integerValue] on it.

Edit: So you're assigning an NSNumber to an int16? That's not gonna work. You should change your variable type.

David Kanarek
I think Canada Dev meant that the attribute "favoritesID" is defined as an Int16 in Core Data which is an NSNumber.
gerry3
Ah, my mistake. I think the first part of my answer is still going to solve his problem.
David Kanarek
Yes. "favoritesID" is an Int16, which I can see in the docs is an NSNumber object.
Canada Dev