Store NSInteger in Core Data

2019-08-23 15:09发布

问题:

Is there any way I can skip dealing with NSNumber and work directly with NSInteger?

回答1:

Core Data will only allow NSNumbers. However, you can write custom getters and setters to use NSInteger properties. mogenerator is a wonderful tool that does that automatically for you: it generates classes with native properties for all your entities.



回答2:

No. NSInteger is just a typedef for a long integer, not an object.

Actual implementation:

#if __LP64__ || NS_BUILD_32_LIKE_64
  typedef long NSInteger;
  typedef unsigned long NSUInteger;
#else
  typedef int NSInteger;
  typedef unsigned int NSUInteger;
#endif

The NSNumber class allows the encapsulation of primitive types (int, float, etc.) into an object, which can then be stored into Property Lists and Core Data.

Example:

float pi = 3.1415;
NSNumber *piNumber = [NSNumber numberWithFloat:pi];

You can then easily access and/or transform the value stored into the NSNumber object:

int piAsInteger = [piNumber intValue];