【发布时间】:2013-05-12 13:23:24
【问题描述】:
我正在使用最新的 SDK 开发 iOS 5.0+ 应用程序。
这段代码出现了一个非常奇怪的错误:
- (NSMutableURLRequest*)setupRequestWithService:(NSString*)service andMethod:(NSString*)method
{
NSString* url = [NSString stringWithFormat:@"%@%@.svc/%@", serverUrl, service, method];
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
// Set authentication token.
NSLog(@"???????????? %@", authenticationToken);
if (authenticationToken == nil)
NSLog(@"NULL AUTHTOKEN");
if ([authenticationToken isEqual:[NSNull null]])
NSLog(@"NSNULL AUTHTOKEN");
if (request == nil)
NSLog(@"NULL REQUEST");
[request addValue:authenticationToken forHTTPHeaderField:REQUEST_HEADER_AUTH_TOKEN];
return request;
}
这是我的日志:
???????????? <null>
NSNULL AUTHTOKEN
-[NSNull length]: unrecognized selector sent to instance 0x3b5a5090
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull length]: unrecognized selector sent to instance 0x3b5a5090'
似乎authenticationToken 是NULL。但我不明白,如果authenticationToken 是NULL,为什么我在日志上看不到NULL AUTHTOKEN。
我第二次运行该方法时收到此错误,第一次,我没有收到任何错误。这是我的日志:
???????????? (null)
NULL AUTHTOKEN
顺便说一句:
NSString* authenticationToken;
有什么建议吗?
也许某处有Memory Leak...
【问题讨论】:
-
它是 NSNull,而不是 nil。 developer.apple.com/library/ios/#documentation/cocoa/reference/…
-
你需要检查 if([NSNull null]== authenticationToken){NSLog(@"NULL AUTHTOKEN");}
-
是的,您可能从 JSON 中获得了 authenticationToken,并且该值有一个 null,因此提供给您的是一个 NSNull 对象。您实际上可以使用
authenticationToken == [NSNull null]来测试这一点,因为应用程序中只有一个 NSNull 对象。 -
@HotLicks 如果您将评论添加为答案,我可以接受。