Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Thursday, February 11, 2016

boolValue not converting the NSString to BOOL

boolValue not converting the NSString to BOOL


I know this doubt could be silly mistake. I am getting a variable from JSON string, it will have the status 1 or 0. If I do using first method(Code 1) it works. But if I do the second method (Cord 2) I am getting NO always. I don't know what am I doing wrong. Please forgive me if the question is too silly.

Cord 1:

NSDictionary *drivingAlertResponse = [jsonResponseString objectFromJSONString];  BOOL isEnabled;          if ([[drivingAlertResponse valueForKey:@"alertStatus"] intValue] > 0) {              isEnabled = TRUE;          }else{              isEnabled = FALSE;          }  

Cord 2:

BOOL isEnabled = [[[NSString stringWithFormat:@"%i",[drivingAlertResponse valueForKey:@"alertStatus"]] isEqualToString:@"1"]? @"TRUE": @"FALSE"   boolValue];  

Answer by CrimsonDiego for boolValue not converting the NSString to BOOL


%i is not a valid format specifier. To format an integer, you should use %d. However, at the point where you are doing that, you are trying to format [drivingAlertResponse valueForKey:@"alertStatus"] into an integer when it is still an object (possibly an NSString, or an NSNumber). The specifier for an object is %@. However, you could simply do [[drivingAlertResponse valueForKey:@"alertStatus"] boolValue] and be done with it, because both NSNumber and NSString have a boolValue method.

Answer by Martín Marconcini for boolValue not converting the NSString to BOOL


Why are you using %i? if the value is 0 or 1 you should use %d.

You can try:

BOOL isEnabled = [drivingAlertResponse valueForKey:@"alertStatus"] != 0  

Answer by Paresh Navadiya for boolValue not converting the NSString to BOOL


BOOL value = YES = TRUE = 1 and value = NO = FALSE = 0   

Do this:

BOOL isEnabled = [[NSString stringWithFormat:@"%@",[drivingAlertResponse valueForKey:@"alertStatus"]] intValue];  

Answer by FreeAsInBeer for boolValue not converting the NSString to BOOL


I would just use NSString's boolValue method. You can use it like so:

NSDictionary *drivingAlertResponse = [jsonResponseString objectFromJSONString];  BOOL isEnabled = [[drivingAlertResponse valueForKey:@"alertStatus"] boolValue];  

Answer by Ladislav for boolValue not converting the NSString to BOOL


I would just use

int returnBoolInt = [[drivingAlertResponse valueForKey:@"alertStatus"] intValue];    BOOL isEnabled = [[NSNumber numberWithInt:returnBoolStr] boolValue];  


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.