问题
An NSNumber can store different primitive types, like short, int, long, long long, float, double
But does the size change, when i do
@(long long)
in comparison to
@(int)
By modeling the CoreData model, i use Integer16, Integer32, Integer64, but does it have an outcome on the size of the database, as all is NSNumber?
To a CoreData property, which has in model defined Integer16
long long tmp = 83324;
NSNumber * numberStoringLongLong = @(tmp);
cdEntity.propertyInteger16 = numberStoringLongLong;
long long tmp2 = [cdEntity.propertyInteger16 longLongValue];
Would propertyInteger16 behave right? Would tmp2 be valid?
回答1:
Your first example will not work as intended. Even if NSNumber can store short, int, long and long long, Core Data dynamically creates custom accessors for the properties that
depend on how you defined the type in the Core Data Model.
A quick test with "Integer 16/32/64" attributes shows that behaviour:
NSNumber *n = @(0x11223344556677);
[cdEntity setValue:n forKey:@"i16"];
[cdEntity setValue:n forKey:@"i32"];
[cdEntity setValue:n forKey:@"i64"];
NSLog(@"%@", cdEntity);
Output:
<NSManagedObject: 0x7491030> (entity: Entity; id: 0x7491090 <x-coredata:///Entity/t4521AA03-435E-4683-9EAF-ED6EED5A5E6A2> ; data: {
i16 = 26231;
i32 = 1146447479;
i64 = 4822678189205111;
})
As you can see, storing an integer attribute that does not fit into the declared size of the property does (silently) truncate the value.
So in your example, storing 83324 = 0x1457C in an Integer 16 attribute will
truncate that value to 17788 = 0x457C, and that is what you will get back, even if you
use longLongValue.
回答2:
It shouldn't make a difference. As I understand it, when you allocate an NSNumber, it reserves a specific amount of memory as required in order to represent itself. When you make changes to the value of an NSNumber it should still be taking up the same amount of size in the database regardless of what actual value it's holding (same way an int is still an int whether it's set to 1 or 2147483647).
I'm too lazy to check, but if you're in xcode under openDeveloperTools>instruments there's an allocations tool and a leaks tool. You could run a for-loop and intentionally leak @(int) values, then @(longlong) values and see if there's a difference in how fast it consumes heap.
来源:https://stackoverflow.com/questions/17107787/nsnumber-what-to-be-aware-of-when-using-and-storing-different-primitive-types