I am calling a web service in my project, for handling web service result there is a method, which tells what is returned by service. Other methods use this value for further process.
network problem, webserivce problem or any xyz reason, webserivce handling method return (null) value.
Now I have to perform nul checks, two approaches worked for me
if([val isEqualToString:@"(null)"]) ...
if(!val) ...
there are many questions regarding checking null, but not clearing my concepts.
Some says check length if I check the length like val.length it will be 6, because handler method return the “(null)”. And !val I am not clear how this works. Some also says check isKindOfClass [NSNull null] …
Please can any one demystify this null.
Please don’t give comparison of nil vs Nil vs Null …
if(!val)will test ifvalisnull. That should be what you want to use, plain and simple.if(val == nil)is equivalent.[val isEqualToString:@"null"]will, as the name suggests, test ifvalis equal to the string “null” which would most certainly make it notnull.[val isKindOfClass:[NSNull class]]has no relevance to you right now, so don’t worry about it.Edit since you asked for an explanation of
NSNull:Sometimes, you need to be able to store the concept of
nilrather thannilitself.Suppose you wanted an array with
nilinside it. You want your array to look like[obj1, obj2, nil, obj3].You can’t declare an array like
[NSArray arrayWithObjects:obj1, obj2, nil, obj3, nil]because as it goes through the arguments, when it seesnilit’ll stop. This will result in the array[obj1, obj2], which is not what you wanted.So what do you do in a situation like this? You make your array
[NSArray arrayWithObjects:obj1, obj2, [NSNull null], obj3]. Now you have an object in your array, but this particular object is one that everyone in the system has agreed to call “null.” It’s not actually null.What’s really going on here is
[NSNull null]is a singleton. When you call[NSNull null], it returns a static instance ofNSNull. If you call[NSNull null]again, it’ll return that same object, regardless of where you call the method. Because there is exactly oneNSNullinstance in the whole entire world of your app, it’s equivalent to null because there will never be an object at that same address that doesn’t have a null meaning.So, as I said above, it’s not relevant to you at all. You only need
NSNullif you need a legitimate Objective-C object but you want it to be “null.” It’s usually safer to useNSNullthan simply a string@"(null)"or something like that because it could be possible to overwrite the value of that string, mess up the string comparison, sometime down the line you might need to store the string@"(null)"in the same data structure as you’re storing the null object, etc.