Compare to null in objective c - objective-c

I am beginning to find my code littered with:
if([p objectForKey#"somekey"] != [NSNull null]) {
}
Is there shorter (character-wise) comparison for NULL?
Background: I am using the SBJson library to parse a JSON string and there are often null values (by design) for some of the keys.

Nothing built-in, but it would be reasonable and simple to create a function MYIsNull() that would do the comparison you want. Just think through what you want to return in the case that the key is missing.
You may want to go the other way and transform -null into nil. For instance, you could add a category on NSDictionary like this:
- (id)my_nonNullObjectForKey:(NSString *)key {
id value = [self objectForKey:key];
if ([value isEqual:[NSNull null]) {
return nil;
}
return value;
}

I would use
if([[p objectForKey#"somekey"] isEqual:[NSNull null]] || ![p objectForKey#"somekey"]) {
// NSNull or nil
} else {
// Stuff exists...Hurray!
}
It seem to work since [NSNull null] is in fact an "object". Hope it helps!

No, you have to test for NSNull. However, if you're finding your code is being littered by it, you might want to create a #define for it.
Bear in mind also that if p is nil, or if p doesn't have a value for someKey, then [p objectForKey#"somekey"] != [NSNull null] evaluates to YES.
So you probably want something like this:
#define IsTruthy(X) ( X && (X != [NSNull null]) )

Is there shorter (character-wise) comparison for NULL?
[NSNull null] is 13 chars. You can say:
NSNull.null // << 11
(id)kCFNull // << 11
Or make a function:
IsNSNull([p objectForKey#"somekey"]) // << 10 in this case and requires no ==, !=
Or (cringes) use a category:
[p objectForKey#"somekey"].mon_isNSNull // << 13 in this case, but requires no ==, !=
Just be careful how you name that category when dealing with nil receivers.

Since you are using SBJSON, you can easily change its code - you have the source.
I have actually modified SBJSON parser to skip [NSNull null] values. They are not added to the dictionaries and when I call objectForKey:, I never get [NSNull null], I just get nil. Then, in most situation I don't even have to check if the value is nil since calling a method on nil usually gives the result I expect.

If you're just worried about the amount of time your taking to type, consider macros:
#define ISNULL(key) [p objectForKey:key] == [NSNull null]
then
if (!ISNULL(#"somekey")) ...

Pretty sure you can just say
if ([p objectForKey:#"somekey"]) {
}
I don't use NSNull much so I'm not 100% sure but I think it tests as false and any other object tests as true.

Related

null check for dictionary object before call to intvalue still leads to intvalue calls on null object

I get an array of dictionaries back from reading json off a web server and use the following to make sure I got a particular key in the first dictionary in the array before getting its int value:
if([jsonObject[0] objectForKey:#"votes"]!= nil)
{
int votes = [[jsonObject[0] objectForKey:#"votes"] intValue];
[[UserObject userUnique] updateVotes:votes];
}
However, my app still occasionally crashes saying I have called intValue on Null. I have also tried structuring the control statement as
if([jsonObject[0] objectForKey:#"votes"])
but this also leads to the same error/app crashing. My syntax seems in line with accepted answers on SO (Check if key exists in NSDictionary is null or not). Any suggestions for what else/how else I should check the existence of key-value pair for applying intvalue?
Thank you for any advice.
There is a difference between nil and null. nil is not an object: it's a special pointer value. null (as retuned by [NSNull null]) is an object: it's needed because it can be stored in containers like NSDictionary.
NSString *votesString = [jsonObject[0] objectForKey:#"votes"];
if (votesString != nil && votesString != [NSNull null])
{
int votes = [votesString intValue];
[[UserObject userUnique] updateVotes:votes];
}
EDIT: An answer to #SunnysideProductions question
The post you mentioned recommends a way of turning null values into nil values by creating a -safeObjectForKey: method. You are not using -safeObjectForKey:, you are using the default -objectForKey: method.
Be consecutive in your code. Don't run with methods. It would be better add more null- and type-checks in particular in working with json. Let's do it:
if (jsonObject && [jsonObject isKindOfClass:[NSArray class]])
{
NSArray *jsonArray=(NSArray *)jsonObject;
if (jsonArray.count>0)
{
id firstObject=jsonArray[0];
if ([firstObject isKindOfClass:[NSDictionary class]])
{
NSDictionary *jsonDict=(NSDictionary *)firstObject;
id votesNumber=jsonDict[#"votes"];
if (votesNumber && [votesNumber isKindOfClass:[NSNumber class]])
{
int votes=[votesNumber intValue];
[[UserObject userUnique] updateVotes:votes];
}
}
}
}
Now the code is more safe. Does it still crash?
When you call objectForKeyin nullable dictionary, app gets crashed so I fixed this from following way.
- (instancetype)initWithDictionary:(NSDictionary*)dictionary {
id object = dictionary;
if (dictionary && (object != [NSNull null])) {
self.name = [dictionary objectForKey:#"name"];
self.age = [dictionary objectForKey:#"age"];
}
return self;
}

Objective C NSPredicate predicateWithBlock removing nil/null values

I am trying to populate an array by taking an existing array and removing nil values from it. The array was populated from a the JSON response of an http call. Sometimes the array has a null value at the end, and the easiest way to remove that value so I wouldn't have to handle it everywhere in my code would be to use NSArray's filteredArrayUsingPredicate: to assign the variable into the instance variable I use throughout my class.
NSArray *respAgencyList = (NSArray*) [JSON valueForKeyPath:#"xml.path.to.data" ];
NSLog(#"data before filter: %#", respAgencyList);
// prints: ( { domain: "foo.com", name:"foobar"}, "<null>" });
if (respAgencyList != nil && respAgencyList.count > 0) {
agencies = [respAgencyList filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
NSLog(#"Evaluated object is %#", evaluatedObject); //prints <null> for the null value
BOOL ret = evaluatedObject != nil;
return ret;
}]];
}
In the above code the return value is always YES. However, when I put the debugger on and step through it I see:
evaluatedObject = id 0x00000000
Isn't this a null/nil value? What is different about this value compared to nil?
You should also check for NSNull, which can be placed into an NSArray since it is a proper object.
BOOL ret = (evaluatedObject != nil && [evaluatedObject isKindOfClass:[NSNull class]] == NO);
It is impossible for an NSArray to contain a nil element.
Some enumeration methods do hand you nil after the enumeration, as a signal that you've reached the end, but the nil is not in the array — it's just a signal, and you are not expected to do anything serious with it. However, I do not know whether this is one of them.
I suggest that instead of trying to remove nil from the array, which is impossible since nil was never there in the first place, you examine the array directly (log it, look in the debugger, whatever) and assure yourself that what you're trying to do is unnecessary.

How do I test for null in NSDictionary from SBJSON?

I've got an API returning a JSON encoded string of data that returns a real number or "null" as a value. As long as the JSON contains a numeric or string value, everything works as expected. If the key:value pair value is null, the code below crashes.
How do I properly test NSDictionary objectForKey when it's getting a NULL from SBJSON?
When the API returns a null for filetype, the code below crashes at the if() line.
My Objective-C code attempts to test for expected values:
if (1 == [[task valueForKey:#"filetype"] integerValue]) {
// do something
} else {
// do something else
}
The API JSON output:
{"tclid":"3","filename":null,"filetype":null}
The NSLog() output of the NSDictionary is:
task {
filename = "<null>";
filetype = "<null>";
tclid = 3;
}
When transferring data from JSON to a Cocoa collection, the NSNull class is used to represent "no value", since Cocoa collections can't have empty slots. <null> is how NSNull prints itself.
To test for this, you can use someObject == [NSNull null]. It's a singleton -- there's only one instance of NSNull per process -- so pointer comparison works, although you may prefer to follow the usual Cocoa comparison convention and use [someObject isKindOfClass:[NSNull class]].
You're getting the crash because you're sending integerValue to that NSNull object. NSNull doesn't respond to integerValue and raises an exception.
You should first test if there is a value is null, if it is null performing the intValue method may crash your application.
Doing this should do.
if ([[task valueForKey:#"filetype"] isKindOfClass:[NSNumber Class]] && 1 == [[task valueForKey:#"filetype"] integerValue]) {
// do something
} else {
// do something else
}
I hope it helps.

How to detect if NSString is null?

I have a piece of code that detects if a NSString is NULL, nil, etc. However, it crashes. Here is my code:
NSArray *resultstwo = [database executeQuery:#"SELECT * FROM processes WHERE ready='yes' LIMIT 0,1"];
for (NSDictionary *rowtwo in resultstwo) {
NSString *getCaption = [rowtwo valueForKey:#"caption"];
if (getCaption == NULL) {
theCaption = #"Photo uploaded...";
} else if (getCaption == nil) {
theCaption = #"Photo uploaded...";
} else if ([getCaption isEqualToString:#""]) {
theCaption = #"Photo uploaded...";
} else if ([getCaption isEqualToString:#" "]) {
theCaption = #"Photo uploaded...";
}
}
And here's the error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSNull isEqualToString:]: unrecognized selector sent to instance 0x3eba63d4'
Am I doing something wrong? Do I need to do it a different way?
The NULL value for Objective-C objects (type id) is nil.
While NULL is used for C pointers (type void *).
(In the end both end up holding the same value (0x0). They differ in type however.)
In Objective-C:
nil (all lower-case) is a null
pointer to an Objective-C object.
Nil (capitalized) is a null pointer
to an Objective-C class.
NULL (all caps) is a null pointer to
anything else (C pointers, that is).
[NSNull null] is a singleton for situations where use of nil is not possible (adding/receiving nil to/from NSArrays e.g.)
In Objective-C++:
All of the above, plus:
null (lowercase) or nullptr (C++11 or later) is a null pointer to C++ objects.
So to check against nil you should either compare against nil (or NULL respectively) explicitly:
if (getCaption == nil) ...
or let ObjC / C do it implicitly for you:
if (!getCaption) ...
This works as every expression in C (and with Objective-C being a superset thereof) has an implicit boolean value:
expression != 0x0 => true
expression == 0x0 => false
Now when checking for NSNull this obviously wouldn't work as [NSNull null] returns a pointer to a singleton instance of NSNull, and not nil, and therefore it is not equal to 0x0.
So to check against NSNull one can either use:
if ((NSNull *)getCaption == [NSNull null]) ...
or (preferred, see comments):
if ([getCaption isKindOfClass:[NSNull class]]) ...
Keep in mind that the latter (utilising a message call) will return false if getCaption happens to be nil, which, while formally correct, might not be what you expect/want.
Hence if one (for whatever reason) needed to check against both nil/NULL and NSNull, one would have to combine those two checks:
if (!getCaption || [getCaption isKindOfClass:[NSNull class]]) ...
For help on forming equivalent positive checks see De Morgan's laws and boolean negation.
Edit: NSHipster.com just published a great article on the subtle differences between nil, null, etc.
You should use
if ([myNSString isEqual:[NSNull null]])
This will check if object myNSString is equal to NSNull object.
Preferred Way to check for the NSNULL is
if(!getCaption || [getCaption isKindOfClass:[NSNull class]])
if([getCaption class] == [NSNull class])
...
You can also do
if([getCaption isKindOfClass:[NSNull class]])
...
if you want to be future proof against new subclasses of NSNull.
Just check with this code:
NSString *object;
if(object == nil)
This should work.

How to check if an NSDictionary or NSMutableDictionary contains a key?

I need to check if an dict has a key or not. How?
objectForKey will return nil if a key doesn't exist.
if ([[dictionary allKeys] containsObject:key]) {
// contains key
}
or
if ([dictionary objectForKey:key]) {
// contains object
}
More recent versions of Objective-C and Clang have a modern syntax for this:
if (myDictionary[myKey]) {
}
You do not have to check for equality with nil, because only non-nil Objective-C objects can be stored in dictionaries(or arrays). And all Objective-C objects are truthy values. Even #NO, #0, and [NSNull null] evaluate as true.
Edit: Swift is now a thing.
For Swift you would try something like the following
if let value = myDictionary[myKey] {
}
This syntax will only execute the if block if myKey is in the dict and if it is then the value is stored in the value variable. Note that this works for even falsey values like 0.
if ([mydict objectForKey:#"mykey"]) {
// key exists.
}
else
{
// ...
}
When using JSON dictionaries:
#define isNull(value) value == nil || [value isKindOfClass:[NSNull class]]
if( isNull( dict[#"my_key"] ) )
{
// do stuff
}
I like Fernandes' answer even though you ask for the obj twice.
This should also do (more or less the same as Martin's A).
id obj;
if ((obj=[dict objectForKey:#"blah"])) {
// use obj
} else {
// Do something else like creating the obj and add the kv pair to the dict
}
Martin's and this answer both work on iPad2 iOS 5.0.1 9A405
One very nasty gotcha which just wasted a bit of my time debugging - you may find yourself prompted by auto-complete to try using doesContain which seems to work.
Except, doesContain uses an id comparison instead of the hash comparison used by objectForKey so if you have a dictionary with string keys it will return NO to a doesContain.
NSMutableDictionary* keysByName = [[NSMutableDictionary alloc] init];
keysByName[#"fred"] = #1;
NSString* test = #"fred";
if ([keysByName objectForKey:test] != nil)
NSLog(#"\nit works for key lookups"); // OK
else
NSLog(#"\nsod it");
if (keysByName[test] != nil)
NSLog(#"\nit works for key lookups using indexed syntax"); // OK
else
NSLog(#"\nsod it");
if ([keysByName doesContain:#"fred"])
NSLog(#"\n doesContain works literally");
else
NSLog(#"\nsod it"); // this one fails because of id comparison used by doesContain
Using Swift, it would be:
if myDic[KEY] != nil {
// key exists
}
Yes. This kind of errors are very common and lead to app crash. So I use to add NSDictionary in each project as below:
//.h file code :
#interface NSDictionary (AppDictionary)
- (id)objectForKeyNotNull : (id)key;
#end
//.m file code is as below
#import "NSDictionary+WKDictionary.h"
#implementation NSDictionary (WKDictionary)
- (id)objectForKeyNotNull:(id)key {
id object = [self objectForKey:key];
if (object == [NSNull null])
return nil;
return object;
}
#end
In code you can use as below:
NSStrting *testString = [dict objectForKeyNotNull:#"blah"];
For checking existence of key in NSDictionary:
if([dictionary objectForKey:#"Replace your key here"] != nil)
NSLog(#"Key Exists");
else
NSLog(#"Key not Exists");
Because nil cannot be stored in Foundation data structures NSNull is sometimes to represent a nil. Because NSNull is a singleton object you can check to see if NSNull is the value stored in dictionary by using direct pointer comparison:
if ((NSNull *)[user objectForKey:#"myKey"] == [NSNull null]) { }
Solution for swift 4.2
So, if you just want to answer the question whether the dictionary contains the key, ask:
let keyExists = dict[key] != nil
If you want the value and you know the dictionary contains the key, say:
let val = dict[key]!
But if, as usually happens, you don't know it contains the key - you want to fetch it and use it, but only if it exists - then use something like if let:
if let val = dict[key] {
// now val is not nil and the Optional has been unwrapped, so use it
}
I'd suggest you store the result of the lookup in a temp variable, test if the temp variable is nil and then use it. That way you don't look the same object up twice:
id obj = [dict objectForKey:#"blah"];
if (obj) {
// use obj
} else {
// Do something else
}
if ([MyDictionary objectForKey:MyKey]) {
// "Key Exist"
}
As Adirael suggested objectForKey to check key existance but When you call objectForKeyin nullable dictionary, app gets crashed so I fixed this from following way.
- (instancetype)initWithDictionary:(NSDictionary*)dictionary {
id object = dictionary;
if (dictionary && (object != [NSNull null])) {
self.name = [dictionary objectForKey:#"name"];
self.age = [dictionary objectForKey:#"age"];
}
return self;
}
if ( [dictionary[#"data"][#"action"] isKindOfClass:NSNull.class ] ){
//do something if doesn't exist
}
This is for nested dictionary structure