I am getting an array with null value. Please check the structure of my array below:
(
\"< null>\"
)
When I\'m trying to access
Consider this approach:
Option 1:
NSString *str = array[0];
if ( str != (id)[NSNull null] && str.length > 0 {
// you have a valid string.
}
Option 2:
NSString *str = array[0];
str = str == (id)[NSNull null]? nil : str;
if (str.length > 0) {
// you have a valid string.
}
id object = myArray[0];// similar to [myArray objectAtIndex:0]
if(![object isEqual:[NSNull null]])
{
//do something if object is not equals to [NSNull null]
}
if (myArray != (id)[NSNull null])
OR
if(![myArray isKindOfClass:[NSNull class]])
You can use the following check:
if (myArray[0] != [NSNull null]) {
// Do your thing here
}
The reason for this can be found on Apple's official docs:
The NSNull class defines a singleton object you use to represent null values in situations where nil is prohibited as a value (typically in a collection object such as an array or a dictionary).
NSNull *nullValue = [NSNull null];
NSArray *arrayWithNull = @[nullValue];
NSLog(@"arrayWithNull: %@", arrayWithNull);
// Output: "arrayWithNull: (<null>)"
It is important to appreciate that the NSNull instance is semantically different from NO or false—these both represent a logical value; the NSNull instance represents the absence of a value. The NSNull instance is semantically equivalent to nil, however it is also important to appreciate that it is not equal to nil. To test for a null object value, you must therefore make a direct object comparison.
id aValue = [arrayWithNull objectAtIndex:0];
if (aValue == nil) {
NSLog(@"equals nil");
}
else if (aValue == [NSNull null]) {
NSLog(@"equals NSNull instance");
if ([aValue isEqual:nil]) {
NSLog(@"isEqual:nil");
}
}
// Output: "equals NSNull instance"
Taken from https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/NumbersandValues/Articles/Null.html
I found the code for working with NSNull
has the following problems:
So I created the following category:
@interface NSObject (NSNullUnwrapping)
/**
* Unwraps NSNull to nil, if the object is NSNull, otherwise returns the object.
*/
- (id)zz_valueOrNil;
@end
With the implementation:
@implementation NSObject (NSNullUnwrapping)
- (id)zz_valueOrNil
{
return self;
}
@end
@implementation NSNull (NSNullUnwrapping)
- (id)zz_valueOrNil
{
return nil;
}
@end
It works by the following rules:
Class
(ie singleton instance of the Class
type) then behavior is undefined. However, a method declared in a subclass is allowed to override a category method in its super-class. This allows for more terse code:
[site setValue:[resultSet[@"main_contact"] zz_valueOrNil] forKey:@"mainContact"];
. . as opposed to having extra lines to check for NSNull
. The zz_
prefix looks a little ugly but is there for safety to avoid namespace collisions.
Building off of Toni's answer I made a macro.
#define isNSNull(value) [value isKindOfClass:[NSNull class]]
Then to use it
if (isNSNull(dict[@"key"])) ...