Search code examples
objective-ccore-datansnumber

Unable to set 'int' in CoreData as NSNumber


I have an attribute that is described as Int16. It is described in the .h file as NSNumber. No matter how I format it, I can't seem to get the valid value of either 12 or 24 stored in UserDefaults. What am I doing wrong? or, better yet, how do I fix this so aHourFormat is the same as timeFormat?

This is the code:

updateData.aHourFormat = [NSNumber numberWithInt:[preferencesDict objectForKey:@"timeFormat"]];
NSLog(@"\ntimeFormat: %d\naHourFormat: %d",[[preferencesDict objectForKey:@"timeFormat"]intValue],[updateData.aHourFormat intValue]);

This what NSLog displays in the debug console:

timeFormat: 12
aHourFormat: -30496

and

timeFormat: 24
aHourFormat: 14000

This is the definition of aHourFormat:

@property (nonatomic, retain) NSNumber *aHourFormat;

Solution

  • Change:

    updateData.aHourFormat = [NSNumber numberWithInt:[preferencesDict objectForKey:@"timeFormat"]];
    

    To:

    updateData.aHourFormat = [preferencesDict objectForKey:@"timeFormat"];
    

    objectForKey: returns an object. If you cast it to an NSInteger then you'll get a value related to its address; if you then pack that into an NSNumber then that's what you'll get when you later unpack as intValue.

    You just want the object directly.

    You'll otherwise be getting a reliable result because of a thing called tagged pointers, which relates to the way that memory addresses can be used so that there's not really anything in memory on 64-bit platforms. It's not worth worrying about other than to be aware that the dependable result isn't surprising.