【问题标题】:MagicalRecords persisting in background thread with image fetching?MagicalRecords 在后台线程中持续获取图像?
【发布时间】:2013-01-29 19:10:28
【问题描述】:

我有以下代码:

dispatch_async(dispatch_get_main_queue(), ^{
    NSManagedObjectContext *localContext = [NSManagedObjectContext contextForCurrentThread];

    Item *newItem = [Item createInContext:localContext];
    newItem.title = NULL_TO_NIL([itemJson valueForKey:@"title"]);
    newItem.image_url = NULL_TO_NIL([itemJson valueForKey:@"image_url"]);
    newItem.order_id = @([[self largestOrderId] intValue] + 1);

    NSURL *url = [NSURL URLWithString:newItem.image_url];
    NSData *data = [[NSData alloc] initWithContentsOfURL: url];
    if (data == nil) {
        NSLog(@"Image data is nil from %@", url);
    } else {
        NSLog(@"Image fetched in saveItemFromJson for cid:%@ order_id:%@", newItem.cid, newItem.order_id);
        newItem.image = [UIImage imageWithData:data];
    }

    if (![localContext hasChanges]) {
        NSLog(@"No local change detected. Quitting");
        return;
    }

    [localContext saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
        if (!success)
            NSLog(@"Error: %@", [error localizedDescription]);
        else
            NSLog(@"Item persisted for cid:%@ order_id:%@", newItem.cid, newItem.order_id);
    }];
});

我似乎得到了很多以下内容:

2013-02-13 18:55:47.404 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8386a90) → Saving <NSManagedObjectContext (0x8386a90): *** DEFAULT ***> on *** MAIN THREAD ***
2013-02-13 18:55:47.404 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8386a90) → Save Parents? 1
2013-02-13 18:55:47.404 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8386a90) → Save Synchronously? 0
2013-02-13 18:55:47.497 Giordano.iPhone[13956:c07] Image fetched in saveItemFromJson for cid:7218 order_id:10
2013-02-13 18:55:47.497 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8386a90) → Saving <NSManagedObjectContext (0x8386a90): *** DEFAULT ***> on *** MAIN THREAD ***
2013-02-13 18:55:47.498 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8386a90) → Save Parents? 1
2013-02-13 18:55:47.498 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8386a90) → Save Synchronously? 0
2013-02-13 18:55:47.499 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalRecord) MR_contextWillSave:](0x8386a90) Context DEFAULT is about to save. Obtaining permanent IDs for new 10 inserted objects
2013-02-13 18:55:47.501 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8385aa0) → Saving <NSManagedObjectContext (0x8385aa0): *** BACKGROUND SAVING (ROOT) ***> on *** MAIN THREAD ***
2013-02-13 18:55:47.502 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8385aa0) → Save Parents? 0
2013-02-13 18:55:47.502 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8385aa0) → Save Synchronously? 1
2013-02-13 18:55:47.502 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalRecord) MR_contextWillSave:](0x8385aa0) Context BACKGROUND SAVING (ROOT) is about to save. Obtaining permanent IDs for new 10 inserted objects
2013-02-13 18:55:47.505 Giordano.iPhone[13956:c07] __70-[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:]_block_invoke21(0x8385aa0) → Finished saving: <NSManagedObjectContext (0x8385aa0): *** BACKGROUND SAVING (ROOT) ***> on *** MAIN THREAD ***
2013-02-13 18:55:47.505 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8385aa0) NO CHANGES IN ** BACKGROUND SAVING (ROOT) ** CONTEXT - NOT SAVING

带有以下错误消息:

2013-02-13 18:55:47.511 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8385aa0) NO CHANGES IN ** BACKGROUND SAVING (ROOT) ** CONTEXT - NOT SAVING
2013-02-13 18:55:47.512 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8385aa0) NO CHANGES IN ** BACKGROUND SAVING (ROOT) ** CONTEXT - NOT SAVING
2013-02-13 18:55:47.512 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8385aa0) NO CHANGES IN ** BACKGROUND SAVING (ROOT) ** CONTEXT - NOT SAVING
2013-02-13 18:55:47.512 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8385aa0) NO CHANGES IN ** BACKGROUND SAVING (ROOT) ** CONTEXT - NOT SAVING
2013-02-13 18:55:47.513 Giordano.iPhone[13956:c07] -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x8385aa0) NO CHANGES IN ** BACKGROUND SAVING (ROOT) ** CONTEXT - NOT SAVING


2013-02-13 18:55:47.515 Giordano.iPhone[13956:c07] Error: (null)
2013-02-13 18:55:47.515 Giordano.iPhone[13956:c07] Error: (null)
2013-02-13 18:55:47.515 Giordano.iPhone[13956:c07] Error: (null)

我正在避免使用 saveInBackgroundWithBlock,因为它已被弃用(需要更新文档?)

对我的代码有什么问题有任何想法吗?

更新

我的团队认为 MagicalRecord 目前存在太多问题。我们已经将我们的代码从 MR 完全迁移回 CoreData。感谢您的关注。

【问题讨论】:

  • 你的主要目标是什么?

标签: ios objective-c core-data magicalrecord


【解决方案1】:

我遇到了同样的问题!仅当我在没有 MR 的情况下手动保存上下文时才修复它。

这是我的解决方案:

NSManagedObject+MyCategory.h

+ (void)saveDataInBackgroundWithBlock:(void(^)(NSManagedObjectContext *localContext))saveBlock
                           completion:(void(^)(void))completion;

+ (NSManagedObjectContext *)newMergableBackgroundThreadContext;

- (void)saveWithCompletion:(void(^)(void))completion;

.m

+ (NSManagedObjectContext *)newMergableBackgroundThreadContext {
    NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
    context.parentContext = [self mainThreadContext];
    [context.userInfo setObject:[NSNumber numberWithInteger:VKCoreDataManagedObjectContextIDTempBackground]
                         forKey:@"contextID"];
    [context.userInfo setObject:kVKCoreDataManagedObjectContextBackgroundTemp
                         forKey:@"contextDebugName"];
    VKDLog(@"* New mergable backround context created! *");
    return context;
}

+ (void)saveDataInBackgroundWithBlock:(void (^)(NSManagedObjectContext *))saveBlock completion:(void (^)(void))completion {
    NSManagedObjectContext *tempContext = [self newMergableBackgroundThreadContext];
    [tempContext performBlock:^{

        if (saveBlock) {
            saveBlock(tempContext);
        }

        if ([tempContext hasChanges]) {
            [tempContext saveWithCompletion:completion];
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) {
                    completion();
                }
            });
        }
    }];
}

- (void)saveWithCompletion:(void(^)(void))completion {
    [self performBlock:^{
        NSError *error = nil;
        if ([self save:&error]) {
            NSNumber *contextID = [self.userInfo objectForKey:@"contextID"];
            if (contextID.integerValue == VKCoreDataManagedObjectContextIDMainThread) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (completion) {
                        completion();
                    }
                });
            }
            [[self class] logContextSaved:self];
            if (self.parentContext) {
                [self.parentContext saveWithCompletion:completion];
            }
        } else {
            [VKCoreData handleError:error];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) {
                    completion();
                }
            });
        }
    }];
}

这里是使用示例:

[NSManagedObjectContext saveDataInBackgroundWithBlock:^(NSManagedObjectContext *localContext){
// do your stuff with local context
} completion:^{
// handle completion, update UI or something
}];

【讨论】:

    【解决方案2】:

    几周前我在使用 MR 时遇到了类似的问题。最后我决定放弃它,自己做所有事情。不是真正解决您的问题,但我放弃它背后的理由是合理的。您可能需要查看 MR 的实际来源。很大一部分文档是不正确的,相当多的库只能通过阅读源代码来学习。尝试使用 MR 进行后台处理很可能存在问题。

    如果您的代码适用于 iOS6+,那么您应该只使用 Master-Main-Child 上下文设置。使用 dispatch_async 也可能是一个问题。让 Core Data 使用 [NSManagedContext performBlock:] 方法来管理你的线程可能更安全。

    如果您使用的是 iOS5 或更低版本,则 Child 上下文和 performBlock: 代码不起作用。最简单的解决方案是将 Core Data 排除在线程之外。在进入新线程/块之前从核心数据中提取任何需要的信息。将该数据传递到您的块中并执行任何必要的处理。然后在某种字典/对象中将其返回到您的主线程,并在那里执行您的核心数据保存。

    另外,我遇​​到了这个问题,因为我下载了图像并将它们保存到 Core Data 中,你可能想看看我在过去几周提出/解决的与此相关的这些问题。以后可能会省去你拔头发的麻烦:

    Can I access the files used for external binary storage in Core Data?

    这最终导致我使用自己的存储机制而不是 Core Data 来存储文件,并最终导致我遇到这个问题/解决方案:

    Files are no longer readable after updating application to newest version

    【讨论】:

    • 谢谢。我自己也丢了 MR
    【解决方案3】:

    你试过MR_saveOnlySelfWithCompletion:吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-23
      • 2015-07-24
      • 1970-01-01
      • 2018-07-27
      • 1970-01-01
      • 2012-05-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多