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;
}