【问题标题】:iOS UITextField & NSTimer OddityiOS UITextField 和 NSTimer 奇怪
【发布时间】:2011-12-09 20:36:47
【问题描述】:

在每个视图中,我都会实例化一个“KeyHandler”对象,使应用程序能够处理物理键盘输入。

当对象被实例化时,它会创建一个隐藏的 textField 作为第一响应者。

在实例化过程中会调用以下代码:

[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(pollTextField:) userInfo:nil repeats: YES];

投票文本字段如下所示:

-(void) pollTextField:(NSTimer*) timer{
  NSString * str = self.textField.text;
  NSString * lastChar;
  if (!str || [str isEqualToString:@""]) {
    //no new text
  }else{

    lastChar = [str substringFromIndex:[str length] - 1];
    [self determineAction:lastChar];
    lastChar = @"";
    str = nil;
  }
  self.textField.text = @"";
}

当我在物理键盘上按 u 时, self.textField.text == u 。但是,textField 不会变为空白——即使我将其设置为 @""。第二次 pollTextField 被称为 self.textField.text == uu,第三次是 == u 并且它在 u 和 uu 之间循环,即使我没有按任何键。另一个奇怪的是,第一次调用 pollTextField 时 self 总是包含所有正确的实例变量,下一次调用时它们就丢失了,即使 self 仍然是 KeyHandler 实例并且仍然具有相同的内存地址。

编辑:这是我创建 textField 和 keyhandler 的方式:

UITextField* textField = [[UITextField alloc] init];
[self.view addSubview:textField];

keyHandler = [[KeyHandler alloc] initWithTextField:textField];
keyHandler.delegate = self;
[textField release];

【问题讨论】:

    标签: ios ios5 uitextfield nstimer


    【解决方案1】:

    这看起来像是内存问题。

    您是如何在代码中创建文本字段的? 你分配得当吗?

    您是否尝试过逐步调试并检查 textField 是否是 pollTextField 函数中的有效对象?

    只需设置一个断点并在 gdb 控制台 po textField 中输入,看看它会给你什么

    编辑: *好吧,你去了,你的答案就在那里。 Textfield 被创建,分配给视图,然后被释放,所以当你释放它时它的生命周期就结束了。

    视图现在拥有它,但您不能直接引用它。

    将标签值添加到文本字段,然后从标签值中转换:

     UITextField* textField = [[UITextField alloc] init];
    textField.tag = 200;
    [self.view addSubview:textField];
    
    keyHandler = [[KeyHandler alloc] initWithTextField:textField];
    keyHandler.delegate = self;
    [textField release];
    

    然后在您的 pollTextField 函数中执行以下操作:

    UITextField* textField = (UITextField*)[self.view viewWithTag:200];

    所以它看起来像:

    -(void) pollTextField:(NSTimer*) timer{
        UITextField* textField = (UITextField*)[self.view viewWithTag:200];
        NSString * str = textField.text;
        NSString * lastChar;
        if (!str || [str isEqualToString:@""]) {
            //no new text
        }else{
    
            lastChar = [str substringFromIndex:[str length] - 1];
            [self determineAction:lastChar];
            lastChar = @"";
            str = nil;
        }
        textField.text = @"";
    }
    

    【讨论】:

    • pollTextField 虽然在 KeyHandler 中。我将 textField 设置为视图的实例变量并删除了释放调用(因此视图和键处理程序都应该具有对 textField 的引用)。但这并没有解决问题。
    • 我的解决方案不起作用吗?至于使 textField 成为类实例变量并且它不起作用,您必须再次向我们展示一些代码,以便我们知道您做了什么。
    • 不幸的是它没有。由于是周末,我面前没有工作代码,所以我不能在这周之前继续。
    • 我非常确定我的解决方案应该有效。确保不要将 textField 引用为 self.textField 而只是 pollTextField 函数中的 textField。如果它不起作用,请调试它,因为如果 textField 是一个有效的 UITextField 对象。如果没有发生其他事情......
    猜你喜欢
    • 2015-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    相关资源
    最近更新 更多