我正在解析从网络服务返回的 XML。如果它是一个有效用户,那么我应该得到一个长整数。 (例如:2110504192344912815 或 2061128143657912001)。如果它无效,那么我得到一个 0。但是,如果您看到我的代码,我有时会得到 userID 的负值,这会使我的验证代码乱七八糟。有什么建议吗?
NSMutableString *loginString;
NSInteger userID;
-(void)parser:(NSXMLParser *)parser
didEndElement:(NSString *) elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName{
if ([elementName isEqual:@"GetUIDResult"]) {
userID = [loginString longLongValue]; / 0 if invalid password or LONG
[loginString release];
loginString = nil;
}
}
//MY VALIDATION CODE..
NSLog(@"The value of userID is: %ld",userID);
if (userID > 0) {
NSLog(@"YOU ARE NOW LOGGED IN");
}else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Login Validation Error" message:@"Unable to validate Login/Password combination" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
最佳答案
检查 loginString 是否不等于 @"0"
if (![loginString isEqualToString:@"0"]) {
NSLog(@"YOU ARE NOW LOGGED IN");
}
编辑:我刚刚意识到您实际上是在问为什么
。好吧,NSString
longLongValue
方法的文档说
Return Value The long long value of the receiver’s text, assuming a decimal representation and skipping whitespace at the beginning of the string. Returns LLONG_MAX or LLONG_MIN on overflow. Returns 0 if the receiver doesn’t begin with a valid decimal text representation of a number.
所以,发生的事情是 loginString 的值溢出,要么是因为您这样接收它,要么是错误地解析了它。
编辑 2:
我看到你编辑了你的代码。现在你试图将一个 long long 值存储到一个 NSInteger 类型的 variabel:userID 中。这肯定会导致溢出。
关于iphone - 为什么我的 NSInteger 对象中会出现奇怪的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6367002/