问题
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