ars*_*ius 6 core-data ios magicalrecord
我无法使用方法[MagicalRecord saveWithBlock:completion]来保存我的对象.当我切换到使用普通块时,它工作正常.使用2.2版开发.
下面的代码有效,我已经注释掉saveWithBlock:特定部分.executeBlock ...:方法只包装dispatch_async和executeBlockOnMainThread:替换completion:block.
[card.managedObjectContext MR_saveToPersistentStoreAndWait];
//[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) { // Replace this...
[NSObject executeBlockInBackground:^{ // With this...
Card *localCard = [card MR_inContext:[NSManagedObjectContext MR_contextForCurrentThread]]; // MR_inContext:localContext];
NSRange range = [localCard.fragment rangeOfString:localCard.term options:NSCaseInsensitiveSearch];
if (range.location == NSNotFound){
return;
}
NSString *fragmentString = [localCard.fragment stringByReplacingOccurrencesOfString:@" " withString:@"+"];
NSString *url = [NSString stringWithFormat:@"https://www.lingq.com/api/languages/%@/phrases/?word=%@&frag=%@&start=%@", appDelegate.currentLanguage, localCard.term, fragmentString, @(range.location)];
NSMutableURLRequest *request = [LQAPI requestForURL:url body:nil HTTPMethod:@"GET"];
NSData *response = [LQAPI executeURLRequest:request];
NSDictionary *responseDictionary = [LQAPI dictionaryFromJSONData:response];
if (responseDictionary == nil){
return;
}
NSArray *phrases = [responseDictionary objectForKey:@"phrases"];
NSMutableArray *cards = [NSMutableArray array];
int index = 0;
for (NSDictionary *d in phrases){
Card *c = [self cardFromDictionary:d content_id:localCard.content_Id index:index type:BlueCard];
c.parentID = localCard.mId; // This marks it as a phrase
[cards addObject:c];
index++;
}
[localCard.managedObjectContext MR_saveToPersistentStoreAndWait]; // This shouldn't be necessary using saveWithBlock: and it didn't help when I tried it.
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"parentID = %@", localCard.mId];
NSArray *phrases2 = [Card MR_findAllWithPredicate:predicate]; // All the objects appear fine here
[NSObject executeBlockOnMainThread:^{ // This would have been in the completion block below
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"parentID = %@", card.mId];
NSArray *phrases = [Card MR_findAllWithPredicate:predicate]; // This does find phrases
[delegate didFetchPhrases:phrases forCard:card];
}];
}];
/* completion:^(BOOL success, NSError *error) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"parentID = %@", card.mId];
NSArray *phrases = [Card MR_findAllWithPredicate:predicate]; // This doesn't find any phrases
[delegate didFetchPhrases:phrases forCard:card];
}];*/
Run Code Online (Sandbox Code Playgroud)
最后,这是我的错(当然!)。方法 cardFromDictionary: 使用 MR_contextForCurrentThread。传递它 localContext 解决了这个问题。