Decrease index value by one

I populate a TableView with CoreData.

So far I have been doing something like this:

NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath]; 

... to retrieve the object to fill the string.

Everything worked fine until I realized that I needed to manage the first row of the table as an exception, because the first row would contain other content not provided by CoreData.

Now my problem is how can I manipulate indexPath to shift everything by one. I would like to do something like this:

 // I know this is not going to work, just to give you an idea... NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath-1]; 

but I cannot find the correct syntax to control indexPath. Can someone help me? Thanks for your time!

+7
source share
2 answers

In case we are talking about iOS UITableView index paths are much simpler:

 NSIndexPath* newIndexPath = [NSIndexPath indexPathForRow:oldIndexPath.row+1 inSection:oldIndexPath.section]; 

Greetings ... :)

+12
source

If you are talking about the standard iOS UITableView, then your index path is an instance of NSIndexPath and will have two entries: section index and row index. If I understand correctly, you want to reduce the row index by 1 every time you want to fill a table cell. (I assume that you have only one section, or you do not need a section index - if this is not correct, edit your question.)

Basically, you need to create a new instance of NSIndexPath with your adjusted indexes, and then use it to query your recipient for the results. Something like this will work (unverified):

 NSUInteger indexes[2]; [indexPath getIndexes:indexes]; indexes[1]--; NSIndexPath * adjustedIndexPath = [[NSIndexPath alloc] initWithIndexes:indexes length:2]; NSManagedObject * managedObject = [self.fetchedResultsController objectAtIndexPath:adjustedIndexPath]; 

This basically does the following:

  • Pulls existing indexes into an NSUIntegers array C
  • Decreases the last index (at position 1 - the row index) by 1
  • Creates a new NSIndexPath with customized indexes from array C
  • Selects a managed entity using the new pointer path.

Please note that this does not apply to the partition index at all, and therefore will adjust each cell in your table, regardless of whether it is in the first partition. If this is not what you want, either wrap the setting in a conditional (for example, if([indexPath indexAtPosition:0] == 0) ), or add your own logic.

+2
source

All Articles