【问题标题】:Integer value of NSPopUpButton Selected ItemNSPopUpButton 所选项目的整数值
【发布时间】:2015-05-24 19:36:17
【问题描述】:

我正在尝试通过这样做将 NSPopUpButton 中选定项目的字符串值转换为它的 int 值(弹出窗口中的项目是各种数字):

txtUPs = [txtUPs stringByAppendingString:btnUPs.titleOfSelectedItem];
numUPs = (int) txtUPs;
NSLog(@"%i" ,numUPs);

我没有得到整数 6(当我从弹出窗口中选择 6 时),而是得到一个像 26376 这样的巨大数字。我做错了什么?

谢谢, 基思

【问题讨论】:

  • 表达式(int) txtUPs 是一个“类型转换”表达式。您是在告诉编译器简单地表现得好像 txtUPsint。它不会转换或解释或类似的东西。 txtUPs 不是字符串。它是一个变量,它持有一个指向字符串对象的 指针。也就是说,它在内存中保存了一个地址。地址实际上是数字。因此,您告诉编译器将txtUPs 中保存的地址视为int,并将该值分配给numUPs。这就是为什么你会得到一些任意值。这是txtUPs持有的地址。
  • 谢谢大家。我理解 Ken 关于 txtUPs 是指针的观点。

标签: objective-c cocoa


【解决方案1】:

要将字符串转换为其整数值,请使用 integerValue 字符串方法。例如:

NSInteger selectedNumber = [btnUPs.titleOfSelectedValue integerValue];

【讨论】:

  • 使用NSInteger-unsignedIntegerValue。不要将NSUInteger-integerValue 混用。
  • 除此之外,字符串来自 UI,应该是可本地化的。 -integerValue 不做这项工作。
【解决方案2】:

您应该为此使用number formatter。它将以本地化的方式处理转换。 (字符串呈现给用户,因此应该是可本地化的。)

NSString *stringValue = [txtUPs stringByAppendingString:btnUPs.titleOfSelectedItem];
NSNumberFormatter *formatter =[[NSNumberFormatter alloc] init];

// Configure the formatter, if you need to
formatter.numberStyle = NSNumberFormatterDecimalStyle
…

// Convert it
NSNumber *numberValue = [formatter numberFromString:stringValue];
int value = [numberValue intValue];

顺便说一句:从显示的值中获取内部程序值的方法可能会中断:想想像“> 1000”这样的项目或无法由数字格式化程序转换的值表示,即。 e. “10k5”。

【讨论】:

    猜你喜欢
    • 2013-08-06
    • 2012-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多