V2Krazy
V2Krazy

Reputation: 53

tableView cell returning NULL

I am trying to read the text from a tableView cell and in the prepareForSegue method, I would take the text and set it to NSUserDefaults. However, when I NSLog the text, it returns NULL. This is what I've tried.

 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(UITableViewCell *)sender
      {
         NSString *blah = sender.textLabel.text;
         NSLog(@"%@",blah); // It returns NULL no matter what cell is clicked
      }

Upvotes: 1

Views: 224

Answers (2)

Paul.s
Paul.s

Reputation: 38728

In your tableView:cellForRowAtIndexPath: method you will be assigning the cell.textLabel.text to something based on the indexPath.

This could look something like

id myDomainObject = [self objectAtIndexPath:indexPath];

cell.textLabel.text = myDomainObject.text;

So if you can get the indexPath in the prepareForSegue you can get your domain object and from there you can get the text.

Without seeing your tableView:cellForRowAtIndexPath: I can't give much more advice

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

You should not use the label from the cell, because it is part of the view. Although the cell is correct, its visuals may be disposed by the time the prepareForSegue: is called.

The MVC way of doing this would be querying the underlying data source for the data at the cell's row, and use that data instead of the label.

Here is what I mean: somewhere in the implementation of cellForRowAtIndexPath: you have code that looks like this:

NSString *labelData = [myDataSource objectAtIndex:indexPath.row];
cell.textLabel.text = labelData;

You should replicate that code inside your prepareForSegue: method:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(UITableViewCell *)sender
{
    NSUInteger row = [self.tableView indexPathForCell:sender].row
    NSString *labelData = [myDataSource objectAtIndex:row];
    NSLog(@"%@", labelData); // This should work
}

Upvotes: 2

Related Questions