How to get the indexPath from a textField in a cell, when didEndOnExit calls a custom method

StackOverflow https://stackoverflow.com/questions/22996051

  •  01-07-2023
  •  | 
  •  

this is my first question. I wouldn't be asking but after reading the documentation and trying lots of code from stack overflow I'm still stumped. I've just started learning code recently, so yes, I am a dumb-ass and wouldn't be surprised if I've made some fundamental error(s).

What I'm trying to do: in a custom cell's textField, a number is entered and on exit the saveGoal method is called in the CustomCellClass.m (code shown below). The saveGoal method creates a goalsArray from the text file of previous entries (if there's no data the text file is created. I omitted that code because it works). This is where it gets difficult (for me). I need the indexPath of the cell which called the method so I can insert the user entry... But I don't know how to get the cell object to use as a parameter in indexPathForCell.

   - (IBAction)saveGoal:(id)sender {

    // Saving the user entry in a string
    self.goalString = [NSString stringWithFormat:@"%@\n",self.goal.text];

    // Instance variables
    NSError *err = nil;
    NSMutableArray *goalsArray = [NSMutableArray arrayWithContentsOfURL:self.goalsURLMethod];

    // If there is data in the text file
    NSIndexPath *indexPath = [[NSIndexPath alloc] init];

            // Ideally I'd like to do something like this (There is an IBOutlet from the 
            // table view in the storyboard to a tableView property).
            indexPath = [self.tableView indexPathForCell: UNKNOWN CELL PARAMETER]; 

            // Then based on the indexPath I can insert or replace objects in the array
            if(indexPath == 0) {
            // masterful code
            } else {
            // If it's another row, replace the object. Something like this:
            [goalsArray replaceObjectAtIndex: indexPath.row withObject: self.goalString];
            [goalsArray writeToURL:self.goalsURLMethod atomically:YES];

            // Then update the view 
            [self.tableView reloadData];
            }
        }
}

A solution would be much appreciated!

有帮助吗?

解决方案

If you have a custom cell, add a property to it:

@property (strong, nonatomic) NSIndexPath *indexPath;

and set it when you return the cell for display. Now the cell has access to the required information.

Aside:

Not that you're going to use it any more, but don't do this:

NSIndexPath *indexPath = [[NSIndexPath alloc] init];
indexPath = [self.tableView indexPathForCell: UNKNOWN CELL PARAMETER];

because creating an instance just to destroy it in the next statement is wasteful

其他提示

Or you could just do it like this into the action method of your choice:

CGPoint hitPoint = [sender convertPoint:CGPointZero toView:self.tableView]; 
NSIndexPath *hitIndex = [self.tableView indexPathForRowAtPoint:hitPoint];
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top