Nanego Nanego - 5 months ago 15
iOS Question

Issue when getting data from text field in dynamic cell

I have created a dynamic table, but I'm facing an issue when I try to access the content of a text field in the first cell. The textfield I get is always empty, even though I enter some text in it before calling the action.

Here is my code. Could you help me to find what's wrong in it ?


@interface CustomNameCell : UITableViewCell
@property (retain, nonatomic) IBOutlet UITextField *nameTextField;


@interface CustomViewController : UITableViewController
@property (retain, nonatomic) IBOutlet UITableView *tableview;
- (IBAction)search:(id)sender;

CustomViewController.m :

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == 1) {
static NSString *CellIdentifier = @"nameCell";
CustomNameCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==nil) {
cell = [[CustomNameCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
return cell;

and the action when clicking a button, where I try to get the content of the textfield :

- (IBAction)search:(id)sender {

static NSString *CellIdentifier = @"nameCell";
CustomNameCell *nameCell = [_tableview dequeueReusableCellWithIdentifier:CellIdentifier];

here nameCell.nameTextField.text is always equal to @""

Why is my text field always empty ?

Thank you for your help ;)


You shouldn't call [_tableview dequeueReusableCellWithIdentifier:CellIdentifier];within your - (IBAction)search:(id)sender as it is a mechanism to reuse a cell during the creation of your tableView. Instead of creating new cell when you are scrolling your tableview you are reusing some cells you have previously created.

Bottom line: use instead the cellForRowAtIndexPath to access a cell at a specific row in your section and if you want the first cell of the first section it would be:

CustomNameCell * cell = (CustomNameCell *)[tableview cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];