【问题标题】:Trying to save TextField in a TableView试图将 TextField 保存在 TableView 中
【发布时间】:2011-09-15 15:04:01
【问题描述】:
@property (nonatomic, retain) NSString *text;

使用此属性,我可以保存在 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;
}

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

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

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

但是,在 cellForRowAtIndexPath 中将 textField.text 设置回保存的文本。问题是当它这样做时它给了我

-[CFString _isNaturallyRTL]:消息发送到释放的实例 0x2c459ff0

当我在调试器中查看 cellForRowAtIndexPath 中的 self.text 时,它说它是 NSZombie_NSString ...所以不知何故它正在被释放。我尝试将属性设置为复制,使用 [initWithString] 复制字符串...为什么字符串会被释放?

【问题讨论】:

  • 为什么要将 self.text 复制回 textField.text ?你的意思是 indexPath.row ==1 而不是 section ==1 吗?
  • 是的,我的意思是部分。我有 2 个部分,第 0 部分有 7 个由单独数据支持的字段,第 1 部分有 1 个字段,我用 NSString 支持。当视图被回收时,我需要能够使用我的支持数据重新分配 textField.text。
  • 如果你想要的是每个单元格都有一个文本字段,更好的做法是将你的表格视图单元格子类化,并让单元格来管理文本字段的生命周期。

标签: iphone objective-c ios memory-management properties


【解决方案1】:

您在哪里为“文本”属性设置值?

尝试将其设置为self.text = [NSString stringWithFormat:@"This is some text"];

话虽如此,作为最佳实践,我强烈建议不要使用可能与本机对象属性(UILabel.text、UITextField.text 等)混淆的“文本”之类的名称。从长远来看,它会有所帮助:)

【讨论】:

  • 为了保密起见,我通常会更改我在 SO 上的标识符名称。但这是个好建议!
  • 你提到这很有趣,但我今天要继续说下去 :)
【解决方案2】:

一次被咬两次害羞。除了,我已经犯了这个错误。

在我的实际代码中

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

但我的意思是

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

【讨论】:

    【解决方案3】:

    设置

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

    【讨论】:

    • +1 因为这个问题不公平,我的例子会奏效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多