【问题标题】:Going crazy with UITextField用 UITextField 发疯
【发布时间】:2011-11-28 14:03:50
【问题描述】:

这六行代码我真的快疯了。

注意:nomeprezzo 是 2 个文本字段

NSString *itemName = (NSString *) [rowVals objectForKey:@"name"];
NSString *itemPrice = (NSString *) [rowVals objectForKey:@"price"];
nome.text = itemName;
nome.userInteractionEnabled = YES;
prezzo.text = itemPrice;
prezzo.userInteractionEnabled = YES;

不知道为什么当itemPrice 被复制到其中一个标签中时,程序进入 SIGABRT。 相反,如果我尝试使用 NSLog(@"%@",itemPrice); 读取内容,它会返回确切的值,因此这意味着这是一个有效的 NSString

我找到的唯一解决方案是通过NSNumber

NSNumber *itemPrice = (NSNumber *) [rowVals objectForKey:@"price"];
prezzo.text = [[NSString alloc] initWithFormat:@"%@", itemPrice];

还有另一种方法可以直接使用NSString

【问题讨论】:

    标签: objective-c ios nsstring uitextfield nsnumber


    【解决方案1】:

    @"price" 字段中的值可能是 NSNumber,而不是 NSString。 NSLog 方法仍然会提供正确的结果,因为 %@ 用于任何 NSObject 子类,而不仅仅是 NSString。

    【讨论】:

    • 对!我没有检查那个。谢谢。
    【解决方案2】:

    这个怎么样:

    NSString *itemPrice = [[rowVal objectForKey:@"price"] stringValue];
    prezzo.text = itemPrice;
    

    【讨论】:

    • 这是另一个解决方案,确实不错。但我一直在寻找问题。顺便说一句,非常感谢。
    【解决方案3】:

    问题可能是[rowVals objectForKey:@"price"] 返回的对象类型。当您在方法调用之前放置 (NSString *) 转换时,您是在告诉编译器返回什么类型的对象,但实际上并未将其转换为 NSString。您在下面使用的行确实从 NSNumber(或任何其他对象)转换为字符串:[[NSString alloc] initWithFormat:@"%@", itemPrice]

    【讨论】:

      【解决方案4】:

      您可能将 NSNumber 的对象存储在 NSDictionary 而不是 NSString 中。

      可能有两种方法:一种是将 NSNumber 转换为 NSString,同时将其添加到字典中,另一种方法是将 NSNumber 转换为 NSString,同时将其分配给“itemName”。

      您可以为第二个选项进行转换,例如:

      NSString *itemPrice = [[rowVals objectForKey:@"price"]stringValue];
      

      【讨论】:

      • 您的解释是完美的,也是解决方案,但感谢 cpprulez 我可以自己找到解决方案。无论如何,非常感谢您的想法。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-30
      • 2012-11-02
      • 2020-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多