如何在Cocoa中将NSString转换为unsigned int?

时间:2010-05-13 02:26:08

标签: objective-c cocoa nsstring unsigned

我的应用程序获得了NSString,其中包含unsigned int。 NSString没有[myString unsignedIntegerValue];方法。我希望能够从字符串中取出值而不进行修改,然后将其放在NSNumber内。我正试着这样做:

NSString     *myUnsignedIntString = [self someMethodReturningAString];
NSInteger    myInteger            = [myUnsignedIntString integerValue];
NSNumber     *myNSNumber          = [NSNumber numberWithInteger:myInteger];

// ...put |myNumber| in an NSDictionary, time passes, pull it out later on...

unsigned int myUnsignedInt        = [myNSNumber unsignedIntValue];

由于我必须首先将其转换为unsigned int,否则以上可能“切断”大型NSInteger的结尾?或者看起来好用吗?如果它会切断它的结尾,下面怎么样(我认为有点像kludge)?

NSString     *myUnsignedIntString = [self someMethodReturningAString];
long long    myLongLong           = [myUnsignedIntString longLongValue];
NSNumber     *myNSNumber          = [NSNumber numberWithLongLong:myLongLong];

// ...put |myNumber| in an NSDictionary, time passes, pull it out later on...

unsigned int myUnsignedInt        = [myNSNumber unsignedIntValue];

感谢您提供的任何帮助! :)

1 个答案:

答案 0 :(得分:7)

第一个版本截断,第二个版本应该没问题,只要你的数字实际上符合无符号整数 - 参见例如"Data Type Size and Alignment"
但是,您应该使用NSNumber创建+numberWithUnsignedInt

如果你知道编码是合适的,你也可以简单地使用C库:

unsigned n;
sscanf([str UTF8String], "%u", &n);