How to check if BOOL is null?

Is there a way to check if the value is NULL / Nil before assigning a BOOL?

For example, I have a value in NSDictionary, which may have the value TRUE / FALSE / NULL

mySTUser.current_user_following = [[results objectForKey:@"current_user_following"]boolValue]; 

When the value is NULL, I get the following error:

  *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSNull boolValue]: unrecognized selector sent to instance 

I would like to be able to handle the NULL case.

+4
source share
2 answers

You should check [NSNull null] :

 id vUser = [results objectForKey:@"current_user_following"]; if (vUser != [NSNull null]) { // do stuff... } else { // handle the case appropriately... } 
+10
source

At first you can check and assign conditionally, for example. something like the following:

 if (NSValue* val = [results objectForKey:@"current_user_following"]) { mySTUser.current_user_following = [val boolValue]; } 

It:

  • calls objectForKey: twice, storing the result in a variable
  • restricts the scope of a variable to an if
  • works because nil is 0
  • thus executes the assignment operator if val not nil

To further verify that the value is NSNull , you will need to add another test specified by ChristopheD, but I do ask the NSNull question here - YES / NO should be sufficient for a description like "the following."
If you do not have a useful value for the key, you can simply remove it from the dictionary or not insert it in the first place.

+5
source

Source: https://habr.com/ru/post/1308687/


All Articles