在玩具iOS項目中,我使用MagicalRecord在應用程序委託中設置CoreData堆棧。用下面的代碼:NSManagedObjectContext保存但不會持久
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[MagicalRecord setupCoreDataStackWithStoreNamed:@"ToyProject.sqlite"];
[[NSManagedObjectContext MR_defaultContext] setUndoManager:[[NSUndoManager alloc] init]];
...
}
我有NSManagedObject,我正在寫的一個子類(NSRailsManagedObject - 我分叉NSRails並增加CoreData的支持),我已經給了它一個saveContext方法:
- (void)saveContext {
dispatch_async(dispatch_get_main_queue(), ^{
@try {
NSError *error = nil;
if (![self.managedObjectContext save:&error]) {
NSLog(@"Failed to save core data: %@", [error localizedDescription]);
} else {
NSLog(@"\"Successfully\" saved your data.");
}
}
@catch (NSException *exception) {
NSLog(@"Couldn't save your data! Try again later :(");
}
@finally {
NSLog(@"Look, I don't know what else to tell you, mang.");
}
});
}
當我嘗試使用此方法保存此類的子類時,我收到無錯誤,並且保存表面上成功。但是,在應用程序的下一次運行中,上次運行中沒有任何數據存在。相反,如果saveContext方法包含下面的代碼,它的工作原理沒有問題:
- (void)saveContext {
[[NSManagedObjectContext MR_defaultContext] MR_save];
}
而且,如果我雜交兩種,儲蓄不會保留數據。
- (void)saveContext {
dispatch_async(dispatch_get_main_queue(), ^{
@try {
NSError *error = nil;
if (![[NSManagedObjectContext MR_defaultContext] save:&error]) {
NSLog(@"Failed to save core data: %@", [error localizedDescription]);
} else {
NSLog(@"\"Successfully\" saved your data.");
}
}
@catch (NSException *exception) {
NSLog(@"Couldn't save your data! Try again later :(");
}
@finally {
NSLog(@"Look, I don't know what else to tell you, mang.");
}
});
}
我真的不知道還有什麼可以嘗試的。任何人都可以將我指向正確的方向嗎?
您應該檢查MR_defaultContext是在'dispatch_async牽強()'塊與你在主線程中創建的塊相同(我有一種感覺不會)。如果沒有,嘗試設置一個指向它的指針並使用^塊內的指針,即__block NSManagedObjectContext * theContext = [NSManagedObjectContext MR_defaultContext];'然後引用塊中的'theContext'。 – Rog