问题
I am parsing XML that gets returned from a web service. If it is a valid user than I should be getting a long integer back. (for example: 2110504192344912815 or 2061128143657912001). If it is invalid then I get a 0. However if you see my code, I am getting negative values sometimes for userID and that is throwing my validation code hay wire. Any tips?
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];
}
回答1:
check if loginString is not equal to @"0"
if (![loginString isEqualToString:@"0"]) {
NSLog(@"YOU ARE NOW LOGGED IN");
}
EDIT: I jut realised that your are actually asking why
. Well, the documentation for NSString
longLongValue
methods says
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/doc/uid/20000154-intValue
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.
So, what is happening is that loginString's value is an overflow, either because you are receiving it like this, or parsing it wrongly.
EDIT 2:
I saw that you edited your code. Now you are trying to store a long long value into a NSInteger type variabel:userID. This definitely will cause an overflow.
来源:https://stackoverflow.com/questions/6367002/why-am-i-getting-strange-values-in-my-nsinteger-object