[英]NSString Compare Not Working in Objective-C
以下是我试图在两个NSString值之间进行比较的Objective-C代码,但是会引发运行时错误。 这是代码:
NSDictionary *innerContent=[JSONResponseDict valueForKey:@"JSONRESPONSE"];
NSString *authFlag = [innerContent valueForKey:@"authenticationFlag"];
NSLog(@"authFlag = %@",authFlag);
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:nil
message: [NSString stringWithFormat:@"authenticationFlag = %@",authFlag]
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
// This block is problematic
if ( [authFlag isEqualToString:@"1"]){
NSLog(@"Logged in");
self.view = homeView;
} else {
NSLog(@"Not logged in");
}
请注意,NSString authFlag已经过测试,确实具有有效的字符串值。 authFlag的值为“ 1”或“ 0”(它是通过使用json-framework对JSON调用的响应获得的)。
这是运行时错误:
[Session started at 2009-03-29 19:21:00 -0700.]
2009-03-29 19:21:11.186 taggle[4144:20b] userEmail=user@domain.com&password=opensesame
2009-03-29 19:21:11.653 taggle[4144:20b] authFlag = 1
2009-03-29 19:21:11.655 taggle[4144:20b] *** -[NSCFBoolean isEqualToString:]: unrecognized selector sent to instance 0xa089c400
2009-03-29 19:21:11.661 taggle[4144:20b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSCFBoolean isEqualToString:]: unrecognized selector sent to instance 0xa089c400'
如错误日志所示,authFlag不是NSString
,而是NSCFBoolean
。
你可以这样做:
NSCFBoolean *authFlag = [innerContent valueForKey:@"authenticationFlag"];
if([authFlag boolValue]) {
NSLog(@"Logged in");
self.view = homeView;
} else {
NSLog(@"Not logged in");
}
您的authFlag是NSNumber,而不是NSString。
NSCFBoolean是NSNumber的私有子类。 它属于类集群设计模式。
NSNumber中没有名称为isEqualToString:的方法。
这是修改后的代码。
NSNumber *authFlag = [innerContent valueForKey:@"authenticationFlag"];
if([authFlag boolValue]) {
NSLog(@"Logged in");
self.view = homeView;
} else {
NSLog(@"Not logged in");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.