我正在使用MagicalRecord更好地更改自定义CoreData功能。
我有两个实体:Offer(视频游戏提供)和System(控制台,PC,etx)。商品可以包含一个或多个系统,我从Parse查询中获取所有数据,然后保存所有数据。
我只有8个系统,所以当我的应用程序启动时,我会获取所有这些并保存魔法记录。然后我调用我的方法获取一些提议并将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];
}];
}
}
我做错了什么?
感谢您的时间
答案 0 :(得分:1)
这行代码存在几个可能的问题
System *system = [System MR_findFirstByAttribute:@"key" withValue:systemKey inContext:localContext];
因此,首先检查 - 获取所有系统实体并记录'key'值。确保您的密钥确实存在。
其次,最好重构代码以保存后台
+ (void)initializeSystemsWithCompletion:(void (^)())completion
{
[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
NSArray *systemsKeys = [[self systems] allKeys];
for (NSString *systemKey in systemsKeys) {
System *system = [System MR_findFirstByAttribute:@"key" withValue:systemKey inContext:localContext];
if (system == nil) {
system = [System MR_createEntityInContext:localContext];
}
system.key = systemKey;
system.name = [self literalForSystem:systemKey];
system.subscribed = [NSNumber numberWithBool:NO];
}
} completion:^(BOOL success, NSError *error) {
}];
}