使用NSNumberFormatter将NSString转换为NSNumber时崩溃

时间:2013-02-26 22:41:55

标签: ios nsnumberformatter

我在NSSTRING中有一个简单的值,我希望将其转换为NSNumber。我一直在我的代码中这样做,出于某种原因,这次它不起作用。你觉得这有什么不对吗?

NSNumberFormatter * num_formatter = [[NSNumberFormatter alloc] init];
[num_formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *score;
NSString *mystr = [[player ScoresArray] objectAtIndex:currentKeeper - 1];


NSLog(@"here is my string: -%@-", mystr);
score = [num_formatter numberFromString:mystr];   // crash occurs on this line.  see error below...
NSLog(@"now it is: %d", [score intValue]);        // it never gets to this line...

以下是上述代码的输出:

  

这是我的字符串:-3 -

这是我得到的错误:

2013-02-26 17:21:48.912 Golf Whiz[50407:c07] -[__NSCFNumber isEqualToString:]: unrecognized selector sent to instance 0xcb5fa90
2013-02-26 17:21:48.912 Golf Whiz[50407:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber isEqualToString:]: unrecognized selector sent to instance 0xcb5fa90'
*** First throw call stack:

2 个答案:

答案 0 :(得分:1)

确保您添加到ScoresArray的对象实际上是字符串,而不是NSNumbers。

答案 1 :(得分:0)

谢谢,所有人,如所怀疑的那样,事实证明我在scoresArray中确实拥有了nsnumber对象。我已经在这段代码中从字符串到数字来回走动,以至于我的脑袋即将爆炸。对于这个蹩脚的问题感到抱歉 - 如果可以的话,我现在会对我自己的问题进行投票... lol