我有代码,我正在从iOS 4移植到iOS 3.2,用于iPad上的演示项目。我有这个密码:
+(int) parseInt:(NSString *)str
{
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
[nf setAllowsFloats:NO];
[nf setMaximum:[NSNumber numberWithInt:INT_MAX]];
[nf setMinimum:[NSNumber numberWithInt:INT_MIN]];
@try {
NSNumber *num = [nf numberFromString:str];
if (!num)
@throw [DataParseException exceptionWithDescription:@"the data is not in the correct format."];
return [num intValue];
}
@finally {
[nf release];
}
}
这项工作在iOS 4上进行,当字符串(例如日期,我遇到问题)出现时抛出异常:
1/1/2010
出于某种原因,num不是nil,它有值
1
,而在iOS 4上,它是零。我最初是用
NSScanner
因为这比
NSNumberFormatter
但是我遇到了同样的问题,它没有解析整个字符串,只是字符串中的第一个数字。
我可以做些什么来解决这个问题吗,或者我必须手动创建一个int解析器。我不想使用基于C的方法,但如果必须,我会的。
+(int) parseInt:(NSString *)str
{
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
[nf setAllowsFloats:NO];
[nf setMaximum:[NSNumber numberWithInt:INT_MAX]];
[nf setMinimum:[NSNumber numberWithInt:INT_MIN]];
@try {
IF_IOS4_OR_GREATER
(
NSNumber *num = [nf numberFromString:str];
if (!num)
@throw [DataParseException exceptionWithDescription:@"the data is not in the correct format."];
return [num intValue];
)
else {
NSNumber *num = nil;
NSRange range = NSMakeRange(0, str.length);
NSError *err = nil;
[nf getObjectValue:&num forString:str range:&range error:&err];
if (err)
@throw [DataParseException exceptionWithDescription:[err description]];
if (range.length != [str length])
@throw [DataParseException exceptionWithDescription:@"Not all of the number is a string!"];
if (!num)
@throw [DataParseException exceptionWithDescription:@"the data is not in the correct format."];
return [num intValue];
}
}
@finally {
[nf release];
}
}
当我试图解析字符串时,得到一个EXC_BAD_访问信号
1/1/2001
. 有什么想法吗?
(iOS 4或更高版本定义如下:
http://cocoawithlove.com/2010/07/tips-tricks-for-conditional-ios3-ios32.html
我有一个新的错误:当我解析这个数字时,它不再是精确的(就像在使用相同的浮点代码时它有多个小数点一样)。。。。我该怎么解决??(我可以用@joshpaul的答案……)