I've created two objects in my model, Account and Friend - where 1 Account will have many Friends. I have created these two objects in code also.
I am using a UITableView to show my Accounts (all fine), and using a new UIViewController to add a new record. In the new record I am adding the Account details, and getting friends from an API. When going from the UITableView to the new UIViewController I am creating an empty Account object: UIViewController.account = account;
Now the tricky part. When saving this data I am doing the following:
// 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");
}
}
Now this seems to work - however sometimes my app crashes with a bus error - usually on the device rather than the simulator. Is this the right way to save an Account and many Friends at once? Also - any reason why I would get a bus error? It seems to happen when there开发者_高级运维 are many Friends....
I think there's an error in the line:
friend = [NSEntityDescription insertNewOb...
You need to declare the type of your variable:
Friend *friend = [NSEntityDescription insertNewObj...
(Assuming your Friend class is named Friend
.)
Also, I wouldn't commit the changes every time around the loop. Make the changes, and then, when you're finished, commit them:
for(NSArray *names in usernameArray) //usernameArray holds my Friends
{
// ...
}
// Commit the change.
NSError *error;
if (![context save:&error]) {
// Handle the error.
NSLog(@"save error");
}
精彩评论