将字符串转换为UInt16 Objective-C

时间:2014-04-04 20:18:22

标签: string int converter uint16

我遇到了问题,我无法将字符串或int转换为UInt16。这是我当前的代码:(UInt16)[[defaults stringForKey:@"port"] intValue] [[defaults stringForKey:@"port"] intValue] 8080(UInt16)[[defaults stringForKey:@"port"] intValue]变为51075这是错误的。有谁知道这样做?

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

我找到了自己的答案:

NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init];
    NSString *port = [defaults stringForKey:@"port"];
    UInt16 portNumber = [[formatter numberFromString:port] unsignedShortValue];