Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IF statement issue in IOS using NSString

My if statement won't work. active returns 1 but will not work in the IF statement

JSONDecoder *jsonKitDecoder = [JSONDecoder decoder];
NSDictionary *dict  = [jsonKitDecoder objectWithData:jsonData]; 

NSString *userid = [dict valueForKeyPath:@"users.user_id"];
NSString *active = [dict valueForKeyPath:@"users.active"];

NSLog(@"%@",userid);    // 2013-06-20 03:03:21.864 test[81783:c07] (74)
NSLog(@"%@",active);    // 2013-06-20 03:03:21.864 test[81783:c07] (1)

if ([active isEqualToString:@"1"]){
    // Do something
}

I can't seem to get this IF to work. Do I need to change the NSString to a int?

like image 287
Cliffordwh Avatar asked Jul 04 '26 22:07

Cliffordwh


2 Answers

For starters, use a modern style for retrieving values from dictionaries, rather than valueForKeyPath:.

NSDictionary* users = dict[@"users"];
id active = users[@"active"];

Once you're using a modern style, my guess is that the active value is actually an NSNumber representing a boolean value. So your if block would read:

if([active isKindOfClass:NSNumber] && [active boolValue]) {
    //active is an NSNumber, and the user is active
}
like image 118
Idles Avatar answered Jul 09 '26 05:07

Idles


The syntax of your if statement is just fine. I would try the alternate method for retrieving values from a dictionary as mentioned above.

NSString *active = @"1";

if ([active isEqualToString:@"1"])
{
    // Do something
    NSLog(@"It works!");
}

like image 26
Benjamin Stark Avatar answered Jul 09 '26 04:07

Benjamin Stark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!