Managedobject在UIViewController中变为nil

时间:2015-03-18 09:27:32

标签: ios objective-c core-data

当我尝试在视图控制器中加载其属性时,Managedobject变为零。我的操作流程如下。我的所有操作都发生在主线程(thread1)中。

  1. 我在MOC1中保存了一个新实体。
  2. 然后我在MOC2中获取这个新创建的实体(我已经订阅了NSManagedObjectContextDidSaveNotification,并且在MOC1中完成的更改被合并到MOC2)。
  3. 然后将检索到的Managed Object设置为singleton class的属性。
  4. 之后我加载一个视图控制器。
  5. 当我尝试从singleton类获取managedobject的属性时,内部视图控制器,我得到nil。
  6. 这里我从moc2

    创建一个managedobject
    ManagedObjectClass* someClass = (ManagedObjectClass*)[NSEntityDescription insertNewObjectForEntityForName:@"ManagedObjectClass" inManagedObjectContext:moc2];
    
        someClass.orderID = @"123";
        NSError *error = nil;
        moc2 save:&error];
    

    //下面是我的NSManagedObjectContextDidSaveNotification处理程序

    - (void) mocDidSaveNotification:(NSNotification *)notification
    {
        NSManagedObjectContext *savedContext = [notification object];
    
        // ignore change notifications for the main MOC
        if ([CoreDataController sharedCoreDataController].moc2 == savedContext)
        {
            return;
        }
    
        dispatch_async(dispatch_get_main_queue(), ^{
            [[CoreDataController sharedCoreDataController].moc1 mergeChangesFromContextDidSaveNotification:notification];
        });
    }
    

    //现在使用moc1

    获取创建的someClass
    dispatch_async(dispatch_get_main_queue(),^{
    
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"ManagedObjectClass" inManagedObjectContext:moc1];
        [fetchRequest setEntity:entity];
    
        NSPredicate *matchedPredicate = [NSPredicate predicateWithFormat:@"orderID = 123"];
        [fetchRequest setPredicate:matchedPredicate];
    
        NSError *error = nil;
        NSMutableArray *fetchedObjects = [[[moc1 executeFetchRequest:fetchRequest error:&error]mutableCopy]autorelease];
    
        // Here am able to see the contents of currentOrder
        [appcontroller sharedAppController].currentOrder = [fetchedObjects objectAtIndex:0]
    
    });
    

    //现在加载视图控制器

    DetailsViewController *aSelectedViewController = [[DetailsViewController alloc]initWithNibName:@"DetailsViewController" bundle:nil];
    UINavigationController aNavigationController = [[[UINavigationController alloc] initWithRootViewController:aSelectedViewController]autorelease];
    self.applicationWindow.rootViewController = navigationController;
    

    //查看控制器的实现

    @implementation DetailsViewController
    
    - (void)viewDidLoad
    {
        if([appcontroller sharedAppController].currentOrder == nil)
        {
            NSLog(@"currentOrder became nil");
        }
    }
    @end
    

0 个答案:

没有答案