core-data – 使用Core Data存储unsigned long long

这个问题的变化已被问到herehere,但似乎问题没有得到明确的答案.

我面临的问题是MPMediaLibrary框架将每个MPMediaItem(音乐,视频,播客,…)的引用保持为一个使用的long long(uint64_t),但我似乎无法找到存储此值的方法使用核心数据.使用Integer 64作为数据类型似乎不起作用,我没有看到替代方案.

最佳答案
由于Core Data中不支持unsigned long long,因此您可能需要自己完成“诀窍”.

其中一个想法是将值存储为…二进制数据,并定义将数据作为uint64_t返回的自定义访问器:

// header
@interface Event : NSManagedObject

@property (nonatomic, retain) NSData * timestamp;

- (void)setTimestampWithUInt64:(uint64_t)timestamp;
- (uint64_t)timestampUInt64;

@end


// implementation
@implementation Event

@dynamic timestamp;

- (void)setTimestampWithUInt64:(uint64_t)timestamp
{
    self.timestamp = [NSData dataWithBytes:&timestamp length:sizeof(timestamp)];
}

- (uint64_t)timestampUInt64
{
    uint64_t timestamp;
    [self.timestamp getBytes:&timestamp length:sizeof(timestamp)];
    return timestamp;
}

@end

它似乎做了这个工作.代码如下:

Event *event = [NSEntityDescription insertNewObjectForEntityForName:@"Event"
                inManagedObjectContext:self.managedObjectContext];

uint64_t timestamp = 119143881477165;
NSLog(@"timestamp: %llu", timestamp);

[event setTimestampWithUInt64:timestamp];
[self.managedObjectContext save:nil];

NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Event"];
Event *retrievedEvent = [[self.managedObjectContext executeFetchRequest:request
                           error:nil] lastObject];
NSLog(@"timestamp: %llu", [retrievedEvent timestampUInt64]);

输出:

2012-03-03 15:49:13.792 ulonglong[9672:207] timestamp: 119143881477165
2012-03-03 15:49:13.806 ulonglong[9672:207] timestamp: 119143881477165

像这样的hack当然会增加一个间接级别,并且当大量使用时间戳时它可能会影响性能.

转载注明原文:core-data – 使用Core Data存储unsigned long long - 代码日志