RGriffiths
RGriffiths

Reputation: 5970

Difficulty loading integer from Core Data

I have an integer stored in my core data and set as type integer 32. I can read and write to core data fine and all is well with text and dates etc. But I seem to have difficulty with the integer values.

The entity is Status and I am trying to retrieve both the lastMessageDate and the lastMessageID fields. There is only ever going to be one record in this entity. The date is retrieved fine but the integer not.

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Status"];
NSError *error = nil;
self.updateStatus = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];

NSDate *lastSavedMessageDate = [[self.updateStatus objectAtIndex:0] lastMessageDate];
NSInteger lastSavedMessageID = [[self.updateStatus objectAtIndex:0] lastMessageID];

What is retrieved is not the actual number stored. I guess this is could be to do with pointers, but no matter what I try I can't seem to get the number that is actually stored.

An associated problem is when I am trying to save to this field. The date saves fine but including the integer save I get an error:

for (NSManagedObject *updatedRecord in [self updateStatus])
{
[updatedRecord setValue:now forKey:@"lastMessageDate"];
[updatedRecord setValue:newMessageID forKey:@"lastMessageID"];
}
NSError *errorUpdate;
[context save:&errorUpdate];

Implicit conversion of 'NSInteger' (aka 'int') to 'id' is disallowed with ARC

Any suggestions?

Upvotes: 0

Views: 30

Answers (1)

Marcus S. Zarra
Marcus S. Zarra

Reputation: 46728

As others have stated you need to use NSNumber the reason for this is that Core Data only deals in objects where integer is a primitive. When you populate a number value of any form in a Core Data entity it must be a NSNumber which with the new auto boxing available is fairly trivial.

Converting a NSNumber to a primitive is as simple as calling the right method on the object, in this case it would be -intValue.

Upvotes: 2

Related Questions