views:

208

answers:

1

I am using a predicate to find an object in core data. I can successfully find the object that I want, but I need to also get the indexPath of that object, so that I can push a details view in for that object. Currently I have the following code for getting my object:

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setEntity:[NSEntityDescription entityForName:@"Ride" inManagedObjectContext:self.managedObjectContext]];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title = %@ AND addressFull = %@", view.annotation.title, view.annotation.subtitle];
    [fetchRequest setPredicate:predicate];
    NSMutableArray *sortDescriptors = [NSMutableArray array];
    [sortDescriptors addObject:[[[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES] autorelease]];
    [sortDescriptors addObject:[[[NSSortDescriptor alloc] initWithKey:@"addressFull" ascending:YES] autorelease]];
    [fetchRequest setSortDescriptors:sortDescriptors];
    [fetchRequest setReturnsObjectsAsFaults:NO];
    [fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:@"title", @"addressFull", nil]];
    NSError *error = nil;
    NSArray *fetchedItems = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    // Sohow what record we returned
    NSLog(@"%@",[fetchedItems objectAtIndex:0]);

So, I can correctly get my object into an array. But how do I translate that object into an indexPath?

+2  A: 

An index path is just a set of indices, e.g. {0, 2} might represent an index path pointing at the first section and third row of a table view — assuming a table view representation of your array data is your ultimate goal.

That index path could point to any particular object in your array, depending on how you translate the path to an index of your array.

If you want to make an arbitrary index path, it's pretty easy:

NSUInteger myFirstIndex = 0;
NSUInteger mySecondIndex = 2;
NSUInteger myIndices[] = {myFirstIndex, mySecondIndex};
NSIndexPath *myIndexPath = [[NSIndexPath alloc] initWithIndexes:myIndices length:2];
// ...do someting with myIndexPath...
[myIndexPath release];

So what you need to do is figure out how your array structure translates to sections and rows (again, assuming you want to make a table view representation).

Another option is to use an NSFetchedResultsController to handle table view updates for you — it will handle index paths for you, depending on how you partition your sections.

Alex Reynolds
Yes, you are right, I want to show it in a UITableView. Just wanting to slide in the details view for the map annotation that was clicked.
Nic Hubbard
I would recommend that you put your data fetch into an `NSFetchedResultsController` and let it do the table view updates. It eliminates about 99% of the work of hooking up a Core Data fetch result to a table view.
Alex Reynolds
I got it working, just needed to init with my root controller.
Nic Hubbard