【发布时间】:2015-07-02 16:17:47
【问题描述】:
我正在使用 MagicalRecord 以更好的方式更改我的自定义 CoreData 函数。
我有两个实体:Offer(视频游戏优惠)和 System(控制台、PC 等)。一个 Offer 可以有一个或多个系统,我从 Parse 查询中获取所有数据,并保存我的所有数据。
我只有 8 个系统,所以当我的应用程序启动时,我会获取所有系统并使用 Magical Record 保存。然后我调用我的方法来获取一些报价并将 PFObjects 从 Parse 转换为实体。
就是这样
+ (void)createOrUpdateOffersWithArray:(NSArray *)objects completion:(void (^)())completion
{
[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
for (PFObject *object in objects) {
Offer *offer = [Offer MR_findFirstByAttribute:@"offerId" withValue:object.objectId inContext:localContext];
if (offer == nil) {
offer = [Offer MR_createEntityInContext:localContext];
}
// Here I set all the offer values (title, date, etc)...
NSSet *offerSavedSystems = [offer mutableSetValueForKey:@"systems"];
if (offerSavedSystems == nil) {
offerSavedSystems = [[NSMutableSet alloc] init];
}
/* This is a set of all the systems related with the offer */
NSArray *offerSystems = [object objectForKey:@"sistemas"];
NSMutableSet *updatedSystems = [[NSMutableSet alloc] init];
/* Here I query one of my System entities for each in the "offerSystems" array */
for (NSString *systemKey in offerSystems) {
System *system = [System MR_findFirstByAttribute:@"key" withValue:systemKey inContext:localContext];
[updatedSystems addObject:system];
}
offer.systems = updatedSystems;
}
} completion:^(BOOL contextDidSave, NSError *error) {
/* UI update*/
}];
}
奇怪的事情发生在最后一个 for 循环中。尽管我确信所有 8 个系统都在我的 CoreData 模型中,但这条线
System *system = [System MR_findFirstByAttribute:@"key" withValue:systemKey inContext:localContext];
返回零
但最奇怪的是,像这样在 for 循环之前使用 NSLOG
NSLog(@"SYSTEMS %d", [System MR_countOfEntities]);
NSLog(@"SYSTEMS WITH LOCAL CONTEXT %d", [System MR_countOfEntitiesWithContext:localContext]);
我知道了
SYSTEMS 8
SYSTEMS WITH LOCAL CONTEXT 0
我的系统以前是用这种方法保存的
+ (void)initializeSystems
{
NSArray *systemsKeys = [[self systems] allKeys];
for (NSString *systemKey in systemsKeys) {
System *system = [System MR_findFirstByAttribute:@"key" withValue:systemKey];
if (system == nil) {
system = [System MR_createEntity];
}
[MagicalRecord saveWithBlockAndWait:^(NSManagedObjectContext *localContext) {
system.key = systemKey;
system.name = [self literalForSystem:systemKey];
system.subscribed = [NSNumber numberWithBool:NO];
}];
}
}
我做错了什么?
感谢您的宝贵时间
【问题讨论】:
标签: ios core-data magicalrecord