2010-01-14 26 views
0

我在我的模型中,客戶和朋友創建了兩個對象 - 其中1個帳戶將有很多朋友。我也在代碼中創建了這兩個對象。正確的方式將關係數據添加到核心數據

我使用一個UITableView顯示我的賬戶(無一不精),並使用新的UIViewController添加一個新的記錄。在新記錄中,我添加了帳戶詳細信息,並從API獲取朋友。當從UITableView到新的UIViewController時,我創建一個空的Account對象:UIViewController.account = account;

現在棘手的問題。當保存這個數據我做了以下內容:

// Configure the new account with information from the form. 
[account setUsername:[profileDict objectForKey:@"the_name"]]; 
[account setPassword:password.text]; // from formfield 
[account setCreationDate:[NSDate date]]; 

// Commit the change. 
NSError *error; 
if (![account.managedObjectContext save:&error]) { 
    // Handle the error. 
    NSLog(@"save error"); 
} 

NSManagedObjectContext *context = [account managedObjectContext]; 

for(NSArray *names in usernameArray) //usernameArray holds my Friends 
{ 

    friend = [NSEntityDescription insertNewObjectForEntityForName:@"Friend" inManagedObjectContext:context]; 
    [account addReplyAccountsObject:friend]; 
    [friend setName:[names objectAtIndex:0]]; 
    [friend setPicUrl:[names objectAtIndex:1]]; 

    // Commit the change. 
    NSError *error; 
    if (![context save:&error]) { 
     // Handle the error. 
     NSLog(@"save error"); 
    }  
} 

現在,這似乎工作 - 但有時我的應用程序崩潰,總線錯誤 - 通常是設備而不是模擬器上。這是保存帳戶和許多朋友的正確方法嗎?還有 - 爲什麼我會得到一個公交車錯誤的原因?看來當有許多朋友發生....

回答

1

我認爲有該行的錯誤:

friend = [NSEntityDescription insertNewOb... 

需要聲明的變量的類型:

Friend *friend = [NSEntityDescription insertNewObj... 

(假設你的朋友類命名爲Friend

而且,我也不會繞環路每次提交更改。進行更改,然後在完成後提交它們:

for(NSArray *names in usernameArray) //usernameArray holds my Friends 
{ 
    // ... 
} 

// Commit the change. 
NSError *error; 
if (![context save:&error]) { 
    // Handle the error. 
    NSLog(@"save error"); 
}  
+0

感謝 - 朋友在我的.h文件中聲明爲朋友*朋友。 – mootymoots 2010-01-14 10:12:18

+1

如果你在這樣的循環中插入新的朋友對象,那麼在你的頭文件中聲明它是一個非常糟糕的主意。你應該使用一個局部變量,否則'朋友'只會引用輸入的最後一個對象。更不用提你不必要地提及臨時數據。 – 2010-01-14 20:23:11

+0

@mootymoots:出於興趣,是否將提交代碼移出循環修復了錯誤?另外,正如@Marcus S. Zarra所說,一次又一次地設置相同的實例變量是一個糟糕的主意 - 改用局部變量。 – 2010-01-14 21:41:57