Showing posts with label null. Show all posts
Showing posts with label null. Show all posts

Friday, June 3, 2011

Creating an Empty Array

To create an empty array use NSNull:

NSNull *myNull = [NSNull null];
NSMutableArray *arr = [NSMutableArray arrayWithObjects: myNull, myNull, nil];


Then to compare use something like:

if ([arr objectAtIndex:index]  == (id)[NSNull null]) {

  //do something
}


nil cannot be added into an Array or collection similar to how an int cannot be added.  NSNull is the helper object to get nil into the collection.  In Objective C there's nil, NSNull and Null.

NSNull, nil, null differences

Found a great answer on stack overflow.  Here's the gist of it:

nil is like (NSObject *)0
NULL is like (void*)0
Both are pointers with an integer value of zero.

NSNull is a helper object to add nil to NSArray or container classes requiring an object.  Similar to how NSNumber is needed to add an int.  [NSNull null] can be used instead of nil.  You can't compare NSNull to nil, but you can check if something is a NSNull.

Tuesday, July 13, 2010

How to check if bool is null.


A handy way to check if a stored bool value does not exist.  originally from http://stackoverflow.com/questions/2760112/how-to-check-if-a-bool-is-null
You can test first and assign then conditionally, e.g. something like the following:
if (NSValue* val = [results objectForKey:@"current_user_following"]) {
    mySTUser.current_user_following = [val boolValue];
}
This:
  • avoids calling objectForKey: twice by storing the result in a variable
  • limits the scope of the variable to the if statement
  • works because nil is is equivalent to 0
  • thus only executes the assignment statement if val is not nil
To additionally check for the value being NSNull you'd have to add another test as given by ChristopheD, but i question wether NSNull is really needed here - YES/NO should be sufficient for a description like "is following".
If you have no useful value for a key, you could simply remove it from the dictionary or not insert it in the first place.