iPhone - 核心数据崩溃 - 多个托管对象上下文

Posted

技术标签:

【中文标题】iPhone - 核心数据崩溃 - 多个托管对象上下文【英文标题】:IPhone - Crash in core data - multiple managed object context 【发布时间】:2010-12-25 17:41:24 【问题描述】:

所以,我正在使用多线程的核心数据。每个人都有自己的托管对象上下文。 我得到一个无法识别的选择器异常,所以我很好奇我是否做错了什么。 崩溃显然与“mergeChanges”方法有关。 我将不胜感激。

编辑 问题似乎是 myManagedObjectContext 返回一个已释放的对象。 怎么可能?

My code:

- (NSManagedObjectContext *) myManagedObjectContext 


    NSManagedObjectContext * result = [[[NSThread currentThread] threadDictionary] objectForKey: AQPerThreadManagedObjectContext];
    if ( result != nil )
        return result;

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator!=nil)
    


    NSManagedObjectContext * moc = [[NSManagedObjectContext alloc] init];
    [moc setMergePolicy: NSMergeByPropertyObjectTrumpMergePolicy];
    [moc setPersistentStoreCoordinator: coordinator];
    [self StoreManagedObjectContextForCurrentThread:moc];
    [moc release];      // now owned by the thread dictionary
    return moc ;
    
    else 
        GTMLoggerError(@"FAILED TO return managed object context ");

    


    return nil; 


-(void) StoreManagedObjectContextForCurrentThread:(NSManagedObjectContext*) context

    [[[NSThread currentThread] threadDictionary] setObject: context forKey: AQPerThreadManagedObjectContext];


-(BOOL) saveChanges

    BOOL success = YES;
    NSManagedObjectContext* moc = [self myManagedObjectContext];

    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; 

    [nc addObserver:self
           selector:@selector(mergeChanges:)
               name:NSManagedObjectContextDidSaveNotification
             object:moc];

        NSError *error = nil;
        if ([moc save:&error] == NO)
        
                    success = NO;
            GTMLoggerError(@"Failed to save to data store: [%@], [%@]", 
                           [error localizedDescription],
                           [error userInfo]);
        


 return success;
  
- (void)mergeChanges:(NSNotification *)notification


    NSManagedObjectContext* moc = [self myManagedObjectContext];

    AppDelegate * delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *mainContext = [delegate mainThreadMOC];

    // Merge changes into the main context on the main thread
    [mainContext performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:)
                                  withObject:notification
                               waitUntilDone:YES];  

    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; 

    [nc removeObserver:self name:NSManagedObjectContextDidSaveNotification object:moc];
 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions


    mainThreadMOC = [[NSManagedObjectContext alloc]init];
    [mainThreadMOC setMergePolicy: NSMergeByPropertyObjectTrumpMergePolicy];
    [mainThreadMOC setPersistentStoreCoordinator: [[DatabaseManager sharedManager] persistentStoreCoordinator]];



    [[DatabaseManager sharedManager] StoreManagedObjectContextForCurrentThread:mainThreadMOC];
.....
.....

由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[NSKeyPathExpression _processReferenceQueue:]:无法识别的选择器已发送到实例 0xa65940”

0   CoreFoundation                      0x3587a987 __exceptionPreprocess + 114
1   libobjc.A.dylib                     0x34a8249d objc_exception_throw + 24
2   CoreFoundation                      0x3587c133 -[NSObject(NSObject) doesNotRecognizeSelector:] + 102
3   CoreFoundation                      0x35823aa9 ___forwarding___ + 508
4   CoreFoundation                      0x35823860 _CF_forwarding_prep_0 + 48
5   CoreData                            0x356ea3d5 -[NSManagedObjectContext(_NSInternalNotificationHandling) _processReferenceQueue:] + 24
6   CoreData                            0x3573032b -[NSManagedObjectContext mergeChangesFromContextDidSaveNotification:] + 842
7   CoreFoundation                      0x35818bbf -[NSObject(NSObject) performSelector:withObject:] + 22
8   Foundation                          0x31181795 __NSThreadPerformPerform + 268
9   CoreFoundation                      0x358307dd __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 12
10  CoreFoundation                      0x358025b7 __CFRunLoopDoSources0 + 382
11  CoreFoundation                      0x35801e5b __CFRunLoopRun + 230
12  CoreFoundation                      0x35801c87 CFRunLoopRunSpecific + 230
13  CoreFoundation                      0x35801b8f CFRunLoopRunInMode + 58
14  GraphicsServices                    0x320c84ab GSEventRunModal + 114
15  GraphicsServices                    0x320c8557 GSEventRun + 62
16  UIKit                               0x341dc329 -[UIApplication _run] + 412
17  UIKit                               0x341d9e93 UIApplicationMain + 670

【问题讨论】:

【参考方案1】:

不确定这是否是问题所在,但您应该始终从函数返回自动释放值。

你在做:

[moc release];      // now owned by the thread dictionary
return moc ;

但不管线程字典中的所有权如何,它应该是:

return [moc autorelease];

【讨论】:

嗨,不知道为什么,但目前没有发生崩溃,所以它可能解决了我的问题。这有点奇怪,因为无论如何我希望 moc 会被时间线程字典保留整个时间。 会稍等片刻,如果没有出现,会将您的答案标记为已接受。谢谢老兄

以上是关于iPhone - 核心数据崩溃 - 多个托管对象上下文的主要内容,如果未能解决你的问题,请参考以下文章

iPhone托管对象删除崩溃

iPhone核心数据递归关系

从 iphone 的核心数据中删除对象时应用程序崩溃

从 NSMutableArray 中删除对象时崩溃

通过对象的枚举属性使用 NSPredicate 获取核心数据托管对象的问题

核心数据导致 iPhone 崩溃