Is there any way to store unsigned long in core da

2019-02-18 04:52发布

CoreData provides Integer 16, Integer 32 and Integer 64 storage, but doesn't support any sign qualifiers. You can store an unsigned int (32 bit) as a signed long (64 bit) and make sure the value is preserved for the full range, but an unsigned long seems to require a 128 bit signed integer to store, which of course isn't supported by CoreData. Is there any way then to store unsigned long in coreData?

4条回答
对你真心纯属浪费
2楼-- · 2019-02-18 05:33

You could always convert [de]serialize it as a string. It isn't particularly clean, but it gives you the ability to store it as long as you can parse it back into an unsigned long.

查看更多
我想做一个坏孩纸
3楼-- · 2019-02-18 05:33

An unsigned long is not 128bits (yet).
(or do you have a 128bits CPU?)

On a Mac, depending on your CPU architecture, it may be 32 or 64 bits.

See with:

NSLog( @"%u", sizeof( unsigned long ) );

So basically an unsigned long will be compatible will Integer32 or Integer64.

查看更多
相关推荐>>
4楼-- · 2019-02-18 05:39

[Previous comment promoted to answer]

Sounds like it is the bit pattern which is important to you and not the integer value per se. You can store it as a signed - just cast it as C signed<->unsigned casts don't enforce mathematical correctness and just preserve the bits. Cast it back to use it.

Follow up question:

In general yes in (Obj-)C(++) you can store an unsigned integer value into a variable with the equivalent signed integer type, and vice-versa. C casts from signed -> unsigned by definition equate to a bit-copy when using 2's complement integers and the two types are the same size. Going the other way, unsigned -> signed, is "implementation defined" - which in practice usually means a bit-copy. Clang & GCC use a bit-copy for both, but if you want to be absolutely certain you can use a union:

unsigned long r;
long l;

r = (unsigned long)l; // will always work (cast optional)

// following is l = (long)r (cast optional) without "implementation defined" risk
{ union { long sValue; unsigned long uValue; } tmp; tmp.uValue = r; l = tmp.sValue;}

But seriously I doubt anybody would! (Note: Clang at least will compile it down to a straight assignment (bit-copy).)

查看更多
在下西门庆
5楼-- · 2019-02-18 05:42

If you really need the full precision of 64 bit unsigned, you can make it transformable (check the documentation about storing Non-Standard Persistent Attributes). CoreData let's you store just about anything that way. But you probably don't need the full 64-bit precision...?!?

查看更多
登录 后发表回答