开发者

Insert/Modify NSManagedObject with ArrayController and TableView

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.


The problem is the array controller has not had time to fetch its new content based on your MOC changes. This typically happens in a future (possibly the very next) trip through the run loop as a result of observing the MOC for changes.

If you want to work with a newly-inserted object in an array controller's selection, you'll have to force the array controller to refresh its content. To do this, just send the array controller a -fetch: after you're done with your manipulations, then the newly-inserted object should be present. You can then modify the array controller's selection directly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜