Re: NSTreeController, Core Data and root objects
Re: NSTreeController, Core Data and root objects
- Subject: Re: NSTreeController, Core Data and root objects
- From: Rob Keniger <email@hidden>
- Date: Fri, 6 Nov 2009 10:43:16 +1000
On 06/11/2009, at 7:35 AM, Steve Steinitz wrote:
> Fritz's idea looks much cooler (I might try it) but for a clumsier solution, have you written your own method to add new top-level items? I wonder if an IBAction like this would work:
>
> - (IBAction)
> addVisibleTopLevelItem: sender
> {
> YourEntity *invisibleTop = [self topObject];
> YourEntity *newVisibleTop =
> [NSEntityDescription insertNewObjectForEntityForName: @"YourEntity"
> inManagedObjectContext: [context]];
> [newVisibleTop setParent: invisibleTop]; // does your entity have a setParent?
> // might also need to add a child to inVisibleTop
> [treeController addObject: newVisibleTop];
> [treeController rearrangeObjects]; // needed?
> }
>
> Something along similar lines seems to work for me.
Thanks. What I've tried, which does seem to work, is overriding -insertObject:atArrangedObjectIndexPath: and setting the parent explictly if the item is being inserted at the top level:
- (void)insertObject:(id)object atArrangedObjectIndexPath:(NSIndexPath *)indexPath
{
NodeObject* item = (NodeObject*)object;
//only add the parent if this item is at the top level of the tree in the outline view
if([indexPath length] == 1)
{
//fetch the root item
NSEntityDescription* entity = [NSEntityDescription entityForName:@"NodeObject" inManagedObjectContext:[self managedObjectContext]];
NSFetchRequest* fetchRequest = [[NSFetchRequest alloc] init]; //I'm using GC so this is not a leak
[fetchRequest setEntity:entity];
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"isRootItem == 1"];
[fetchRequest setPredicate:predicate];
NSError* error;
NSArray* managedObjects = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error];
if(!managedObjects)
{
[NSException raise:@"MyException" format:@"Error occurred during fetch: %@",error];
}
NodeObject* rootItem = nil;
if([managedObjects count])
{
rootItem = [managedObjects objectAtIndex:0];
}
//set the item's parent to be the root item
item.parent = rootItem;
}
[super insertObject:object atArrangedObjectIndexPath:indexPath];
//this method just sorts the child objects in the tree so they maintain their order
[self updateSortOrderOfModelObjects];
}
Can anyone see anything wrong with this?
--
Rob Keniger
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden