我正在使用 Magical Record 来帮助保存核心数据和多线程。
我用 GCD 启动了一个新线程。在那个新线程中,我检查是否存在实体;如果不是,我想创建一个新的并保存它。
saveUsingCurrentThreadContextWithBlock^(NSManagedObjectContext *localContext){}
如果在非主线程上调用会返回主线程保存吗?
还是我应该将上下文传递给新线程?
编辑:
在主线程上,我创建一个 MBProgress 指标并创建一个新线程:
MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.mapView animated:YES];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
Person *person = [Person MR_findFirstByAttribute:NAME withValue:self.user.username];
if (person == NULL) {
NSLog(@"SEPERATE THREAD | person %@ does not exist, creating", self.user.username);
person = [Person MR_createEntity];
person.name = self.user.username;
person.uid = self.user.UID;
[[NSManagedObjectContext MR_contextForCurrentThread] MR_saveOnlySelfWithCompletion:^(BOOL success, NSError *error) {
[MBProgressHUD hideHUDForView:self.mapView animated:YES];
Person *person = [Person MR_findFirstByAttribute:NAME withValue:self.user.username];
if (person) {
NSLog(@"COMPLETION BLOCK | person exists: %@", person.name);
}
}];
}
else {
NSLog(@"SEPERATE THREAD | person %@ does", self.user.username);
dispatch_async(dispatch_get_main_queue(), ^{
[MBProgressHUD hideHUDForView:self.mapView animated:YES];
});
}
});
(这种保存方法不是持久化,我重启app找不到Person实体):
2013-03-12 14:25:44.014 SEPERATE THREAD | person iDealer does not exist, creating
2013-03-12 14:25:44.014 SEPERATE THREAD | thread: <NSThread: 0x84ca720>{name = (null), num = 4}
2013-03-12 14:25:44.015 -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x840ec30) → Saving <NSManagedObjectContext (0x840ec30): *** UNNAMED ***> on *** BACKGROUND THREAD ***
2013-03-12 14:25:44.015 -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x840ec30) → Save Parents? 0
2013-03-12 14:25:44.015 -[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:](0x840ec30) → Save Synchronously? 0
2013-03-12 14:25:44.016 -[NSManagedObjectContext(MagicalRecord) MR_contextWillSave:](0x840ec30) Context UNNAMED is about to save. Obtaining permanent IDs for new 1 inserted objects
2013-03-12 14:25:44.132 __70-[NSManagedObjectContext(MagicalSaves) MR_saveWithOptions:completion:]_block_invoke21(0x840ec30) → Finished saving: <NSManagedObjectContext (0x840ec30): *** UNNAMED ***> on *** BACKGROUND THREAD ***
2013-03-12 14:25:44.134 COMPLETION BLOCK | thread: <NSThread: 0x8435f30>{name = (null), num = 1}
2013-03-12 14:25:44.134 COMPLETION BLOCK | person exists: iDealer