NSNumber,当使用和存储不同的原语类型时需要注意什么 [英] NSNumber, what to be aware of when using and storing different primitive types
问题描述
NSNumber可以存储不同的基本类型,如short,int,long,long long,float,double
但是当大小改变时, p>
@(long long)
b $ b
与
比较@(int)
pre>
通过对CoreData模型建模,我使用Integer16,Integer32,Integer64,但是它对数据库的大小有一个结果,因为所有的都是NSNumber? p>
在模型中定义了Integer16的CoreData属性
long long tmp = 83324;
NSNumber * numberStoringLongLong = @(tmp);
cdEntity.propertyInteger16 = numberStoringLongLong;
long long tmp2 = [cdEntity.propertyInteger16 longLongValue];
propertyInteger16会正常吗?
您的第一个示例将会按预期 无效。
您的第一个示例将无法正常工作。解决方案即使
NSNumber
可以存储short,int,long和long long,核心数据动态地为
依赖的属性创建自定义访问器如何在核心数据模型中定义类型。
使用Integer 16/32/64属性的快速测试显示该行为:
NSNumber * n = @(0x11223344556677);
[cdEntity setValue:n forKey:@i16];
[cdEntity setValue:n forKey:@i32];
[cdEntity setValue:n forKey:@i64];
NSLog(@%@,cdEntity);
输出:
code>< NSManagedObject:0x7491030> (entity:Entity; id:0x7491090< x-coredata:/// Entity / t4521AA03-435E-4683-9EAF-ED6EED5A5E6A2> ;; data:{
i16 = 26231;
i32 = 1146447479;
i64 = 4822678189205111;
})
所以,在你的例子中,存储
的属性> 83324 = 0x1457C 在整数16属性将
截断该值到17788 = 0x457C
,这是你会得到,即使你
使用longLongValue
。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?
解决方案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 to17788 = 0x457C
, and that is what you will get back, even if you uselongLongValue
.这篇关于NSNumber,当使用和存储不同的原语类型时需要注意什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!