Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data NSNumber overkill?

Should I use NSNumber or string, for saving a simple "playerID number" that now is an integer because I want to save it with Core Data?

In my datamodel I've got a playerID set to Integer 16 but Core Data want's the NSNumber to work. This seems lika a lot of code for "nothing" - example;

NSInteger myValue = 1;
NSNumber *number = [NSNumber numberWithInteger:myValue];
p1.playerID = number;

// Instead of just;
p1.playerID = 1;
// or
p1.playerID.myIntValue;

Just wondering if it would not be easier to set it to string instead and then convert the value (playerID) back and forth as it's needed? Any words of wisdom (experience) on this? Thank's :-)

like image 700
Mac Avatar asked Dec 19 '25 17:12

Mac


2 Answers

On your entity, define the @property like this:

@property (nonatomic) int32_t playerID;

and then you'll be able to simply set it like

p1.playerID = 1;

This is very elegant and very fast.

In other words, don't define it as being an NSNumber *. But even if you did, performance would still be excellent. It's just easier to read and write code like this. Also note that with the newest Xcode versions, you can use @(myInt) in stead of [NSNumber numberWithInt:myInt].

Make sure to also check out how to use this for enums: Best way to implement Enums with Core Data (look for my answer).

like image 144
Daniel Eggert Avatar answered Dec 21 '25 07:12

Daniel Eggert


NSNumber much more effecient to store value in memory than NSString. Because NSNumber uses a runtime facility called tagged pointers to increase speed and reduce memore usage (See more information)

Also I think that NSNumber takes up less space in CoreData than NSString.

like image 44
Victor Avatar answered Dec 21 '25 09:12

Victor