I've got a document based App using Core Data, and have a tableView which is populated using bindings and an NSArrayController in IB. Everything works fine, but I wanted to make sure that The first column would be in edit mode immediately on adding a new object to the array. I looked around for suitable code and adapted some from the Hillegass book. The editing works fine, but the row selection doesn't seem to be working. It stays at row 0 and when tabbing after editing the next column to be edited is on that row. Here's a version of the code I've used. I've googled for the solution to my problem but keep getting results either without Core Data or bindings, or a non document application. Am I missing something here?
-(IBAction)addEmployee:(id)sender {
Employee *newEmployee = (Employee *)[NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:[self managedObjectContext]];
//Fetch the update Employees
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *employeeEntity = [NSEntityDescription entityForName:@"Employee" inManagedObjectContext:[self managedObjectContext]];
[fetchRequest setEntity:employeeEntity];
NSArray *fetchResults = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error];
[fetchRequest release];
NSError *error = nil;
if (fetchResults == nil) {
// Something here to handle the erro开发者_运维知识库r.
NSLog(@"The fetch results is null");
}
int row = [fetchResults indexOfObjectIdenticalTo:newEmployee];
NSLog(@"row is %d",row);
[[tableView window] endEditingFor:nil];
[tableView editColumn:1 row:row withEvent:nil select:YES];
}
Here's the fixed (and vastly simpified) version
-(IBAction)addEmployee:(id)sender {
Employee *newEmployee = [newEmployeeController newObject];
[newEmployeeController addObject:newEmployee];
[newEmployeeController rearrangeObjects];
NSArray *fetchResults = [newEmployeeController arrangedObjects];
int row = [fetchResults indexOfObjectIdenticalTo:newEmployee];
[[tableView window] endEditingFor:nil];
[tableView editColumn:1 row:row withEvent:nil select:YES];
[newEmployee release];
}
First, you do not need to cast the insertion of the object. -insertNewObjectForEntityForName: inManagedObjectContext:
returns id
so the cast is redudant.
You do not need to fetch the objects just to get the array. You can query the NSArrayController
for the new object you added, if it is not there, add it (sorry been a while since I used an NSArrayController
and don't remember if it needs a cycle of the run loop to detect the change).
From there you can ask the NSArrayController
for the index and go forward.
精彩评论