简体   繁体   中英

NSString Compare Not Working in Objective-C

Following is Objective-C code where I'm trying to do a compare between two NSString values, however it throws a runtime error. Here's the code:

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");
}

Note that the NSString authFlag has been tested as indeed having a valid string value. authFlag either has a value of "1" or "0" (it's gotten from a response to a JSON call using json-framework).

Here's the runtime error:

[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'

As the error log shows, authFlag is not an NSString , but an NSCFBoolean .

You can do this:

NSCFBoolean *authFlag = [innerContent valueForKey:@"authenticationFlag"];

if([authFlag boolValue]) {
    NSLog(@"Logged in");
    self.view = homeView;
} else {
    NSLog(@"Not logged in");
}

Your authFlag is NSNumber and its not NSString.

NSCFBoolean is a private subclass of NSNumber. It comes under class cluster design pattern.

There is no method with the name isEqualToString: available in NSNumber.
Here is the modified code.

NSNumber *authFlag = [innerContent valueForKey:@"authenticationFlag"];

if([authFlag boolValue]) {
    NSLog(@"Logged in");
    self.view = homeView;
} else {
    NSLog(@"Not logged in");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM