Best practice solution for storing “unsigned long long” number in Realm

牧云@^-^@ 提交于 2020-01-05 06:37:05

问题


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:



来源:https://stackoverflow.com/questions/41763199/best-practice-solution-for-storing-unsigned-long-long-number-in-realm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!