Tom Fobear
Tom Fobear

Reputation: 6749

Trying to save TextField in a TableView

@property (nonatomic, retain) NSString *text;

with this property I am saving text from a textfield I create in a UITableViewCell

static NSString *cellIdentifier = @"fieldTableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];

    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 12, 275, 25)];
    textField.clearsOnBeginEditing = NO;
    textField.returnKeyType = UIReturnKeyDone;
    [textField addTarget:self action:@selector(textFieldDone:) forControlEvents:UIControlEventEditingDidEndOnExit];
    [cell.contentView addSubview:textField];
}

// re-get textField and set tag to section
if (section == 1) {
    textField.text = self.text; // Where the problem is
    textField.tag = section;
}

and

- (void)textFieldDone:(id)sender {
    UITextField *field = sender;

    if (field != nil) {
         NSInteger section = field.tag;

        if (section == 1) {
            self.text = field.text;
        }
    }
}

However, back in cellForRowAtIndexPath is setting textField.text back to the saved text. The problem is when it does this it is giving me

-[CFString _isNaturallyRTL]: message sent to deallocated instance 0x2c459ff0

when I look at self.text in cellForRowAtIndexPath in the debugger, it says it is NSZombie_NSString ... so somehow it is getting dealloc'd. I have tried setting the property to copy, copying the string using [initWithString]... Why is the string getting dealloc'd?

Upvotes: 0

Views: 556

Answers (3)

Sid
Sid

Reputation: 9536

Where are you setting a value to the "text" property?

Try setting it as self.text = [NSString stringWithFormat:@"This is some text"];

That being said, as a best practice I highly suggest not using names like "text" that could be confused with native object properties (UILabel.text, UITextField.text, etc.). It helps in the long run :)

Upvotes: 1

Tom Fobear
Tom Fobear

Reputation: 6749

once bitten twice shy. Except, Ive already made this mistake.

in my acctual code I had

text = textField.text; //var declared in class

But I meant

self.text = textField.text; //to use the property like in my example

Upvotes: 0

Legolas
Legolas

Reputation: 12345

Set

textField.delegate = self;
tableView.dataSource = self;

Upvotes: 1

Related Questions