Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Narendar Singh

macrumors member
Original poster
Jun 22, 2012
76
0
INDIA
My server is responding some json like below:

"MyData":
[
{
"name": "narendar",
"address": "san rafael"
}
]

some times I get null in name param:

"MyData":
[
{
"name": null,,
"address": "san rafael"
}
]

I am displaying these tow values in two UITextView like below:

if ([myArray objectForKey:mad:"name"])
{
self.name.text = [myArray objectForKey:mad:"name"];
}

then my code get crashed if name comes with null,.

To handle this situation I have changed my code like below and its working now:

if ([myArray objectForKey:mad:"category"] != [NSNull null])
{
// body skips for null, and this code doesn't executes.
self.name.text = [selectedDeal objectForKey:mad:"name"];
}

Now my question is do I need to compare objectForKey with [NSNull null] ?

Please let me know how to handle this situation when server sends null,, at least it should not be crashed.
 
You don't say what you mean by "crash." Most likely you are getting a runtime exception and SIGABRT due to using NSNull null where an NSString* should go.

All the JSON parsers insert NSNull null if the JSON value is null. So you need to avoid code that ends up like this

Code:
self.name.text = [NSNull null];

That code will probably cause a SIGABRT error, which looks like a crash. To avoid that problem you need to check if the value returned from the JSON is NSNull null.
 
JSON was the main reason why I have these 4 categories. Now I use them all the time where I exchange data between internal classes and web/databases.

Code:
#pragma mark -
#pragma mark NSDictionary (nullObjects)
#pragma mark -

@implementation NSMutableDictionary (nullObjects)

- (void)setObjectOrNull:(id)anObject forKey:(id)aKey;
{
    id  goodObject = anObject ? anObject : [NSNull null];
    
    [self setObject:goodObject forKey:aKey];
}

@end

@implementation NSDictionary (nullObjects)

- (id)objectOrNilForKey:(id)aKey;
{
    id  anObject = [self objectForKey:aKey];
    
    if (anObject == [NSNull null])
        return (nil);
    
    return (anObject);
}

@end

#pragma mark -
#pragma mark NSArray (nullObjects)
#pragma mark -

@implementation NSMutableArray (nullObjects)

- (void)addObjectOrNull:(id)anObject;
{
    id  goodObject = anObject ? anObject : [NSNull null];
    
    [self addObject:goodObject];
}

@end

@implementation NSArray (nullObjects)

- (id)objectOrNilAtIndex:(int)idx;
{
    id  anObject = [self objectAtIndex:idx];
    
    if (anObject == [NSNull null])
        return (nil);
    
    return (anObject);
}

@end
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.