I am developing a game with Game Center functionality.
Internally, my game holds all scores in variables of type int64_t
, since that is the required type for reporting scores through the GameKit
API (I assume this is to avoid ambiguity between 32 bit and 64 bit platforms).
So far, so good.
Next, I wish to store the user's hiscore locally (say, in NSUserDefaults
. But a .plist would be equivalent) for when there's no authenticated Game Center player, and also to sync it via iCloud key-value with other devices owned by the user.
I can store the int64_t
hiscore like this:
// (int64_t) _hiscore is an ivar.
// (NSString) _playerID is the authenticated player ID, or else
// "AnonymousUser" when GKLocalPlayer is not authenticated.
[playerData setObject:@(_hiscore) forKey:@"HiScore"];
[[NSUserDefaults standardUserDefaults] setObject:playerData forKey:_playerID];
[[NSUserDefaults standardUserDefaults] synchronize];
...(assuming the "@( )" operator will take proper care in all cases - not sure about this either...), but which NSNumber
method should I use to retrieve the value without risking integer overflow?
All the -*value
methods of the class (e.g. -intValue
, -longValue
, -unsignedIntegerValue
etc.) return types that are platform-dependant (unlike int64_t, which has an explicit byte size). This post gives great info on all the data types on each platform, but it doesn't help with NSNumber
...
I could do a runtime check of the sizes of the distinguishing types of each platform (e.g. see if sizeof(unsigned long)
equals 4 or 8, and use a different method in each case), but that doesn't look elegant. Not that a new architecture will appear any time soon, but...
I could also store the number as a string, as described in this post, but having the dictionary-friendly NSNumber at hand, it feels silly...
What would you recommend?
Use -[NSNumber longLongValue]
. C standard (C99) guarantees long long
to be at least 64 bits.
By the way, the new @(_hiscore)
syntax is equivalent to [NSNumber numberWithLongLong:_hiscore]
if _hiscore
is int64_t
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With