views:

118

answers:

1

Hey there,

I'm using core-data and I have an entity that has an attribute called SID and another called ParentSID.

I'm trying to create a method where I can pass a fetched object from the set and it will return the lineage of that object by checking the ParentSID of each ancestor.

If the ParentSID is > 0 it should loop recursively until it finds an ancestor with the ParentSID of 0. Each time it loops it should add the ancestor to a lineage array.

If the ParentSID is 0 then it is done and should return the lineage array.

Not sure if this makes any sense.

Thanks, Howie

+1  A: 

Are SID and ParentSID relationships or attributes? The situation you're describing sounds like it makes much more sense to implement as a relationship. That way, you can get the parent object by doing this: [object valueForKey:@"parentSID"]. Otherwise, you would need to do a whole fetch request like this:

NSFetchRequest *parentFetchRequest = [[NSFetchRequest alloc] init];
[parentFetchRequest setEntity:[NSEntityDescription entityForName:@"SID" inManagedObjectContext:managedObjectContext];
[parentFetchRequest setPredicate:[NSPredicate predicateWithFormat:@"parentSID == %@", [object valueForKey:@"parentSID"]];
NSArray *parents = [managedObjectContext executeFetchRequest:parentFetchRequest error:nil];
[parentFetchRequest release];
if ([parents count] == 0) {
    // TODO: Handle this error
    return;
}

NSManagedObject *parentSID = [parents lastObject]; 
// Now, at long last, you have a reference to the parent object.

To answer your specific question, I wouldn't do this as a recursive method. You can easily do this iteratively. For example:

NSManagedObject *sid = // get the original object
NSMutableArray *lineage = [NSMutableArray array];
while (sid) {
    NSMutableObject *parent = // get the parent using one of the techniques above
    if (parent)
        [lineage addObject:parent];
    sid = parent;
}
Alex
Thanks for the quick response. SID and Parent SID are attributes. I have one fetch request that returns all the records. My idea was to pass the method a child object and let it loop recursively. each time it loops it would look at all of the records to find the new parent for the current object.I'm going to try your method of using a while statement instead.thanks,Howie
Ward
Just look out for memory usage. However much data you think you'll have, multiply it by 10, because that's how much your users are going to put into your app.
Alex
thanks for the tip
Ward