2
votes

I have a POS type app that uses Core Data to store daily sales transactions using table views. I am attempting to retrieve and update certain Core Date Properties, like daily sales counts, WITHOUT using table views. Table views use row at index path to point to the correct object (row). I am using the Fetched Results controller with a predicate to retrieve the fetched object (row) Question: How do I obtain the index of the fetched row so that I can retrieve and then update the correct property values? All books and examples use table views to change properties.

Entity Product
Product *product;
______________________________   

[self setupFetchedResultsController];        (This returns one object)

product = [NSFetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];  (objectAtIndexPath - Errors of course)
2

2 Answers

4
votes

I think you shouldn't use NSFetchedResultsController in this case. If you don't want to use it in either a UITableView or a UICollectionView, you're probably better of without it. You're probably better of using a NSFetchRequest instead, it's pretty easy to set up:

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Entity"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"someValue=1"];
fetchRequest.predicate = predicate;
NSError *error = nil;
NSArray *array = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];

Now you have a NSArray with all the results, which you could use without having to deal with index paths.

If you're still using a NSFetchedResultController for a table (I'm not sure if you do), those rows will still be updated whenever you make a change.

Update: To update one of the objects returned by the fetch, could be done like this:

Entity *entity = [array firstObject];
[entity setSomeProperty:@"CoreDataIsAwesome"];

NSError *error = nil;
if ([self.managedObjectContext save:&error]) {
    NSLog(@"Entity updated!");
} else {
    NSLog(@"Something went wrong: %@", error);
}
1
votes

You can use the method indexPathOfObject: on your fetched results controller to return the index path of the given object to then do your updates.