iphone - 为什么我的 NSInteger 对象中会出现奇怪的值?

标签 iphone ios nsinteger

我正在解析从网络服务返回的 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 方法的文档说

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.

所以,发生的事情是 loginString 的值溢出,要么是因为您这样接收它,要么是错误地解析了它。

编辑 2:

我看到你编辑了你的代码。现在你试图将一个 long long 值存储到一个 NSInteger 类型的 variabel:userID 中。这肯定会导致溢出。

关于iphone - 为什么我的 NSInteger 对象中会出现奇怪的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6367002/

相关文章:

iphone - 旋转从视频帧获取的 CGImage

iphone - 解密 AES128 加密的数据

iOS 上传文件到谷歌云存储 - 获取 401 : 'Login Required'

ios - 安全区域和导航栏

iphone - corona sdk不支持mp3播放?

ios - isKindOfClass 为测试用例返回不同的值

ios - UIToolbar 不显示 UIBarButtonItem

ios - 在 32 位和 64 位架构上格式化 NS(U)Integer 时类型转换的替代方法?

objective-c - 如何在 objective-c 中反转 NSInteger 或 NSUInteger 的字节顺序

objective-c - 如何检查一个 NSInteger 是否大于另一个 NSInteger?