【发布时间】:2014-02-24 13:34:58
【问题描述】:
我无法使用方法 [MagicalRecord saveWithBlock:completion] 保存我的对象。当我切换到使用普通块时,它工作正常。使用版本 2.2develop。
下面的代码有效,我已经注释掉了 saveWithBlock: 特定部分。 executeBlock...: 方法只是包装了 dispatch_async 和 executeBlockOnMainThread: 替换了 completion: 块。
[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];
}];*/
【问题讨论】:
标签: ios core-data magicalrecord