Best practice solution for storing “unsigned long

2019-07-23 02:57发布

问题:

I have to store large numbers in Realm storage like 14000822124935161134. Currently I store them by changing the type of them to string as follows and then save it:

    NSMutableDictionary *itemInsert = [item mutableCopy];

    if([item valueForKey:@"timestamp"]) {
        unsigned long long timestamp = [[item valueForKey:@"timestamp"] unsignedLongLongValue];
        [itemInsert setObject:[NSString stringWithFormat:@"%llu", timestamp] forKey:@"timestamp"];
    }

    RLMRealm *realm = [RLMRealm defaultRealm];
    [realm beginWriteTransaction];
    [RMember createOrUpdateInRealm:realm withValue:itemInsert];
    [realm commitWriteTransaction];

And the timestamp property of my RLMObject is defined as follows :

@interface RMember : RLMObject
...
@property (nullable) NSString *timestamp;
...
@end

Is there any suitable type rather than string for this type of data in Realm or any better solution?

回答1:

Realm supports long long; it just doesn't support the unsigned variant.

You could simply save the value as long long and provide a getter accessor that explicitly casts it back to unsigned long long when retrieved from the database.

@interface RMember : RLMObject
@property long long timestamp;
@end

unsigned long long timestamp = [[item valueForKey:@"timestamp"] unsignedLongLongValue];

RLMRealm *realm = [RLMRealm defaultRealm];
RMember *myObject = ...;
[realm transactionWithBlock:^{
    myObject.timestamp = (long long)timestamp;
}];

unsigned long long savedTimestamp = (unsigned long long)myObject.timestamp;
NSLog(@"Saved timestamp is %llu", savedTimestamp);

Tested on my iPad Air and it seemed to be working as expected: