manuelBetancurt
manuelBetancurt

Reputation: 16168

Core Data not saving integer properly? When changing from NSString to int

I'm using Core data on my app ok,

i have a problem when saving a number that is supposed to be an integer... when I fetch it from Core Data, it shows strange number value

I know is working because, with the test, having my idTosave = 345, it shows on results of CoreData, but when sending a value [string to int] that I know is woking as it logs the correct response, CD saves a strange value:

(Please note Im saving to entity idRef)

NSLog(@"resultToDisplay:: %@", self.resultsToDisplay);

//    int idToSave = 345; //if I use this line instead of intValue it saves 345 OK!
int idToSave = (int)[self.resultsToDisplay intValue];


NSLog(@"id salvada as NSINTEGER:: %d",idToSave);



//graba a CD!
[Student insertWithDataQR:[studentDataDicto objectForKey:@"name"] surname:[studentDataDicto objectForKey:@"surname"] 
 phone:[studentDataDicto objectForKey:@""] 
 dob:[studentDataDicto objectForKey:@"dob"] idRef:idToSave ...]];

[[Student defaultManagedObjectContext]save:nil]; 

log out:

 resultToDisplay:: 1329955200
  2012-02-26 00:36:08.597 MyGym_iPad[10867:707] id salvada as NSINTEGER:: 1329955200

note the value 1329955200, is correctly showed as integer and string before saving,

and to check the response I do:

  NSArray *studiantes = [Student all];


for ( Student *tud in studiantes) {
    NSLog(@"tu %@ ...%@",tud.studentName, tud.idRef );
}

so, with int 345, i see on the log tu.idRef == 345

but with the int from string, i see on the log tu.idRef == -32384

so If I save from string that goes to int, I get on my response: -32384

edit:

I have subclassed my generated core data class manager file, to save idRef as NSNumber

    studentData.idRef = [NSNumber  numberWithInt:idRef];

edit x2

to check the log i do:

NSArray *studiantes = [Student all];


for ( Student *tud in studiantes) {
    NSLog(@"tu %@ ...%d",tud.studentName, [tud.idRef intValue]);
}

but the result to that is: -32384 ,, for my value casted to int, when saved from string

but the correct value 345,, when just sent an int directly,

Upvotes: 2

Views: 3259

Answers (2)

Franck
Franck

Reputation: 742

You have to put it in a NSNumber:

NSNumber *idToSave = [NSNumber numberWithInteger:[self.resultsToDisplay integerValue]];

EDIT

Actually we've reached the max value, solved with an integer 32 field.

Upvotes: 6

Michael Dautermann
Michael Dautermann

Reputation: 89569

int values can not be Objective C id objects.

Either convert your int to a NSString object or, better than that, use NSNumber objects to contain your int value.

Upvotes: 2

Related Questions