0

合併後我知道我在這裏丟失了不少,但我無法找到任何代碼的教程和它被我逼瘋。創建ManagedObjectContext和併發核心數據更新

我有一個應用程序,示出了在可經由上拉至刷新被更新的表圖(從核心數據拉動)項。更新程序從REST API中提取新數據並將其存儲在覈心數據中,並刷新TableViewController中包含的主數據集。

很顯然,我想拉來刷新是非阻塞的,所以我一個MOC內實現它:performBlock方法調用。一切似乎工作,但我的模型中執行數據庫操作時,我得到隨機的應用程序崩潰,我知道這是因爲我管理我的MOCS和持久對象模型不正確。如果有人能指出我的方向正確,我會很感激。

下面是實際執行數據和表刷新方法。下面我將列出一堆輔助代碼可能有用:

-(void)refresh { 

    NSManagedObjectContext *child = [[NSManagedObjectContext alloc]initWithConcurrencyType:NSPrivateQueueConcurrencyType]; 
    [child setParentContext:self.db]; 

    [child performBlock:^{ 
     model = [[CustomersModel alloc] init]; 
     self.custs = [model getUpdatedCustomers:self.db]; 
     self.workingSet = self.custs; 
     dispatch_async(dispatch_get_main_queue(), ^{ 

      [super performSelector:@selector(stopLoading) withObject:nil afterDelay:1.0]; 
     }); 
    }]; 
} 

-(void)stopLoadingComplete { 

    ... 
    [self.tableView reloadData]; 
} 

這裏設立商務部,持久性數據存儲等我的appdelegate代碼:

- (NSManagedObjectContext *)managedObjectContext 
{ 

    if (__managedObjectContext != nil) 
    { 
     return __managedObjectContext; 
    } 

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; 
    if (coordinator != nil) 
    { 
     __managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType]; 
     [__managedObjectContext setPersistentStoreCoordinator:coordinator]; 
    } 
    return __managedObjectContext; 
} 

這裏是我的分配MOC應用程序委託代碼到UITableViewControllers:

CustomerListViewController *clvc = [[CustomerListViewController alloc] initWithNibName:@"CustomerListViewController" bundle:nil withManagedContext:self.managedObjectContext]; 
clvc.detailViewController = detailViewController; 
UINavigationController *clvcNav = [[UINavigationController alloc] initWithRootViewController:clvc]; 

這裏是我的客戶列表視圖控制器的分配MOC代碼:

customerlistview.h:

#import <UIKit/UIKit.h> 
#import "CustomersModel.h" 
#import "SearchBarTableViewController.h" 

@interface CustomerListViewController : SearchBarTableViewController 
{ 
    CustomersModel *model; 
} 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil withManagedContext:(NSManagedObjectContext *)db; 

@property (retain) IBOutlet UISearchBar *searchBar; 
@property (strong, nonatomic)NSManagedObjectContext *db; 
@property (strong, nonatomic)NSArray *custs, *workingSet; 

@end 

customerlistview.m:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil withManagedContext:(NSManagedObjectContext *)passedDB { 

    self.db = passedDB; 
    return [self initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
} 
+0

不知道這實際上是答案,但加入[self.db保存]後self.workingSet = self.custs;似乎已經做了訣竅 - 我只是沒有保存父上下文後,子上下文完成其事情。我認爲這很複雜,但考慮到子上下文已經正確設置了父項,保存父項後似乎已將子項的保存傳播給父項。 – Darrrrrren

回答

0

我確實要回答這個問題 - 因爲保存父上下文的語境孩子做了之後的事情,我沒有收到一個程序崩潰。