我在保存對託管對象上下文的更改時遇到錯誤,但我的錯誤處理程序出現問題:錯誤爲零,因此給我沒有有用的信息。我有兩個版本的錯誤處理程序。由Xcode中產生的這一個,和它的作品(即,日誌信息中包含有用的錯誤信息):核心數據保存託管對象上下文 - 錯誤指針爲零
AppDelegate.c
- (void)saveContext
{
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil)
{
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
{
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
*/
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
}
但我希望能夠通過成功/失敗(最終,現在我只是中止)+錯誤信息返回給調用者,所以我有這個,這是行不通的(錯誤是零,因此沒有提供有關錯誤的有用信息)。
Database.h
+ (BOOL) commit:(NSError **)error;
Database.c
+ (BOOL) commit:(NSError **)error {
AppDelegate *appDelegate = (AppDelegate*) [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *managedObjectContext = appDelegate.managedObjectContext;
if (managedObjectContext != nil)
{
if ([managedObjectContext hasChanges] && ![managedObjectContext save:error])
{
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
*/
if (error == nil) {
NSLog(@"Unresolved error");
abort();
} else {
NSLog(@"Unresolved error %@, %@", *error, [*error userInfo]);
abort();
//return FALSE;
}
}
return TRUE;
}
return FALSE;
}
我敢肯定我的問題是與指針,並在重定向的層迷路。
[編輯:] 調用的代碼提交:
[Database commit:nil];
我不知道如果我需要這樣的東西添加到提交方法的開始,但我不知道指針:
if (error == nil) {
error = [[NSError alloc] init];
}
1)保存操作是否真的失敗?如果成功,「錯誤」不會被設置爲任何內容。 - 2)你能告訴我們如何調用'commit:'方法嗎? - 3)上述代碼在錯誤情況下中止,因此不能返回錯誤。 –
@MartinR 1)是的,它失敗了。 2)該提交被稱爲傳遞在零...嗯...我想知道這是否是問題。 3)代碼中止(暫時),但它也記錄一個錯誤。我的問題是,我得到的錯誤是第一個(只是「未解決的錯誤」),而不是第二個(有錯誤信息),因爲錯誤=零(也確認錯誤=零通過調試器)。 – Sasha