2012-12-14 59 views
0

我在保存對託管對象上下文的更改時遇到錯誤,但我的錯誤處理程序出現問題:錯誤爲零,因此給我沒有有用的信息。我有兩個版本的錯誤處理程序。由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]; 
} 
+0

1)保存操作是否真的失敗?如果成功,「錯誤」不會被設置爲任何內容。 - 2)你能告訴我們如何調用'commit:'方法嗎? - 3)上述代碼在錯誤情況下中止,因此不能返回錯誤。 –

+0

@MartinR 1)是的,它失敗了。 2)該提交被稱爲傳遞在零...嗯...我想知道這是否是問題。 3)代碼中止(暫時),但它也記錄一個錯誤。我的問題是,我得到的錯誤是第一個(只是「未解決的錯誤」),而不是第二個(有錯誤信息),因爲錯誤=零(也確認錯誤=零通過調試器)。 – Sasha

回答

1

如果commit:被調用nil(來自您的評論),那麼這可能是錯誤。你要調用你的函數有錯誤變量的地址:

NSError *error = nil; 
if (![Database commit:&error]) { 
    // commit failed, "error" contains error message. 
} 

,當然return NO代替abort()commit方法中的錯誤情況。

在您的commit方法中沒有必要分配錯誤消息。如果保存失敗,[managedObjectContext save:error]會這樣做。

1

我想你需要在第二個版本中傳遞錯誤的地址否?

[managedObjectContext save:error] 

應該是:

[managedObjectContext save:&error] 

這允許接收方法來控制哪些指針(指針指向)的引用。

相關問題