My app uses Core Data with a simple model with two entities, 'Category' and 'Item', both with a 'name' attribute and a relationship one-to many (a category has many items).
In IB I have a tableview and a Array Controller for the items. Also a textfield and a comboBox (for user type items name and select a category) and "add" button.
What I want is add a new item and modify it with the user´s item name and category selection.
I have tried this:
- (IBAction)add:sender
{
NSManagedObjectContext *moc = [self managedObjectContext];
NSEntityDescription *itemEntityDescription = [NSEntityDescription entityForName:@"Item" inManagedObjectContext:moc];
NSManagedObject *newItem = [[NSManagedObject alloc] initWithEntity: itemEntityDescription insertIntoManagedObjectContext:moc];
//Modify attribute
[newItem setValue:[textField stringValue] forKey:@"name"];
//Setup category relacionship from user selection on comboBox
NSEntityDescription *categoryEntity = [NSEntityDescription entityForName:@"Category" inManagedObjectContext:moc];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(name LIKE[c] %@)",[comboBox objectValueOfSelectedItem]];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:categoryEntity];
[request setPredicate:predicate];
NSError *error = nil;
NSArray *array = [moc executeFetchRequest:request error:&error];
[newItem setValue:[array objectAtIndex:0] forKey:@"category"];
}
The problem is the new item is not selected in the TableView. And if I use instead [itemsArrayController add:nil];
I can´t access to the new item to modify it.
Any solution? Thanks in advance.