Check if NSDictionary is Null? - iphone

I've tried multiple ways. I know the dictionary is NULL, as the console also prints out when I break there. Yet when I put it in an if( ) it doesn't trigger.
([myDict count] == 0) //results in crash
(myDict == NULL)
[myDict isEqual:[NSNull null]]

It looks like you have a dangling or wild pointer.
You can consider Objective-C objects as pointers to structs.
You can then of course compare them with NULL, or with other pointers.
So:
( myDict == NULL )
and
( myDict == [ NSNull null ] )
are both valid.
The first one will check if the pointer is NULL. NULL is usually defined as a void * with a value of 0.
Note that, for Objective-C objects, we usually use nil. nil is also defined as a void * with a value of 0, so it equals NULL. It's just here to denote a NULL pointer to an object, rather than a standard pointer.
The second one compares the address of myDict with the singleton instance of the NSNull class. So you are here comparing two pointers values.
So to quickly resume:
NULL == nil == Nil == 0
And as [ NSNull null ] is a valid instance:
NULL != [ NSNull null ]
Now about this:
( [ myDict count ] == 0 )
It may crash if you have a wild pointer:
NSDictionary * myDict;
[ myDict count ];
Unless using ARC, it will surely crash, because the myDict variable has not been initialised, and may actually point to anything.
It may also crash if you have a dangling pointer:
NSDictionary * myDict;
myDict = [ [ NSDictionary alloc ] init ];
[ myDict release ];
[ myDict count ];
Then you'll try to send a message to a deallocated object.
Sending a message to nil/NULL is always valid in Objective-C.
So it depends if you want to check if a dictionary is nil, or if it doesn't have values (as a valid dictionary instance may be empty).
In the first case, compare with nil. Otherwise, checks if count is 0, and ensure you're instance is still valid. Maybe you just forgot a retain somewhere.

if (TheDict == (NSDictionary*) [NSNull null]){
//TheDict is null
}
else{
//TheDict is not null
}

To check if a dictionary has nil or NULL data, you can check for the [dictionary count] which will return 0 in all cases

if([NSNull null] != [serverResponseObject objectForKey:#"Your_Key"])
{
//Success
}

All above doesn't work for me but this
if([mydict isKindOfClass:[NSNull class]])
{
NSLog("Dic is Null")
}
else
{
NSLog("Dic is Not Null")
}
Worked for me

Related

How to convert NSNull to nil in Swift?

I want to fetch JSON data from my server and manipulate it upon launch. In Objective-C, I have used this #define code to convert NSNull to nil, since the fetched data might include null at times.
#define NULL_TO_NIL(obj) ({ __typeof__ (obj) __obj = (obj); __obj == [NSNull null] ? nil : obj; })
However, in Swift, is it possible to convert the NSNull to nil? I want to use the following operation (the code is Objective-C's):
people.age = NULL_TO_NIL(peopleDict["age"]);
In the above code, when the fetched data's age key is NULL, then the people object's .age property is set to nil.
I use Xcode 6 Beta 6.
This could be what you are looking for:
func nullToNil(value : Any?) -> Any? {
if value is NSNull {
return nil
} else {
return value
}
}
people.age = nullToNil(peopleDict["age"])
I would recommend, instead of using a custom conversion function, just to cast the value using as?:
people.age = peopleDict["age"] as? Int
If the value is NSNull, the as? cast will fail and return nil.

How to check null value of object in decision statement for Objective C

I am getting a object value from server as null value when NSlog this object.I want to identify it in if-else decision statement. How can I check it because nil have reference to a unknown object which not means NULL.and i can't compare it with zero too.
How can i identify that this value is NULL, i have a crash on this point.I have tried #try - #catch block too but all gone in vain.
Any suggestion for this problem.
As others have pointed out, there are many kinds of "null" under Cocoa/Objective C.
But one further thing to note is that [object isKindOfClass:[NSNull class]] is pointlessly complex since [NSNull null] is documented to be a singleton so you can just check for pointer equality. See Topics for Cocoa: Using Null
So use this :-
if (title == (id)[NSNull null] || title.length == 0 ) title = #"Something";
Note how you can use the fact that even if title is nil, title.length will return 0/nil/false, ie 0 in this case, so you do not have to special case it. This is something that people who are new to Objective C have trouble getting used to, especially coming form other languages where messages/method calls to nil crash.
If you want in detail what is the difference between nil, Nil and null, you can check this article What is the difference between nil, Nil and null.
You can try following code to check for NULL values from server:
if (nil == str || NSNull.null == (id)str) {
//Object has Null value
}
else{
// Object has some value
}
str is string value which contain server value.
This may helps you.
The Best Approach is :
if([yourObject isKindOfClass:[NSNull null]])
{
// yourObject is null.
}
else
{
// yourObject is not null.
}

How to combine the advantages of `int` and `NSInteger`

A seemingly simple question: Can I have some sort of Number object, which can be nil but which I can assign like a primitive int:
like this:
NSNumber *n = nil;
n = 3;
if(n == nil){
// some actions...
} else if (n == 1){
// some actions...
} else {
// some actions...
}
Thanks for your input
The answer is NO. If the variable is an object you can either assign another object,
n = anotherNSNumber;
or, set the value by using properties or by methods,
n = [NSNumber numberWithInt:3];
and, compare the object with another object,
if (n == anotherNSNumber) // Checks the reference
or compare its value by using properties/methods,
if (([n intValue] == 3) || ([n intValue] == [anotherNSNumber intValue]))
The short answer as others have mentioned is "No".
But the following slight modification to you code will achieve a similar result:
NSNumber *nObject = [NSNumber numberWithInt:3];
int n = nObject.intValue; // Zero if nObject is nil
if(nObject == nil){
// some actions...
} else if (n == 1){
// some actions...
} else {
// some actions...
}
Not the way you think you can. No.
when you say:
NSNumber *n = nil;
what you are saying is declare a pointer that points to an NSNumber object, but for now have it point to nil This is okay; because what you might do later is to get a pointer to an NSNumber object and then assign it to this variable so that n is then a pointer no a valid NSNumber object.
With your next line:
n = 3;
You are not assigning a value to the object, but you are saying that n points to the address 3. Which isn't an address and which doesn't contain an object.
No, you can't. The reason for that is that nil is a pointer to the address 0x0 i.e. nil == 0. So you won't be able to disambiguate between 0 and nil.
Not to mention the fact they are also supposed to be different types. nil is used as a pointer whereas a number like 0 or 3 is a scalar.
nil is defined as
#define nil NULL
A typical definition of NULL goes like this:
#define NULL ((void *)0)

How to check if a BOOL is null?

Is there a way I can check to see if a value is NULL/Nil before assigning it to a BOOL?
For example, I have a value in a NSDictionary that can be either TRUE/FALSE/NULL
mySTUser.current_user_following = [[results objectForKey:#"current_user_following"]boolValue];
When the value is NULL I get the following error
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSNull boolValue]: unrecognized selector sent to instance
I would like to be able to handle the NULL case.
You should check for [NSNull null]:
id vUser = [results objectForKey:#"current_user_following"];
if (vUser != [NSNull null]) {
// do stuff...
}
else {
// handle the case appropriately...
}
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.

How do I test if a primitive in Objective-C is nil?

I'm doing a check in an iPhone application -
int var;
if (var != nil)
It works, but in X-Code this is generating a warning "comparison between pointer and integer." How do I fix it?
I come from the Java world, where I'm pretty sure the above statement would fail on compliation.
Primitives can't be nil. nil is reserved for pointers to Objective-C objects. nil is technically a pointer type, and mixing pointers and integers will without a cast will almost always result in a compiler warning, with one exception: it's perfectly ok to implicitly convert the integer 0 to a pointer without a cast.
If you want to distinguish between 0 and "no value", use the NSNumber class:
NSNumber *num = [NSNumber numberWithInt:0];
if(num == nil) // compare against nil
; // do one thing
else if([num intValue] == 0) // compare against 0
; // do another thing
if (var) {
...
}
Welcome to the wonderful world of C. Any value not equal to the integer 0 or a null pointer is true.
But you have a bug: ints cannot be null. They're value types just like in Java.
If you want to "box" the integer, then you need to ask it for its address:
int can_never_be_null = 42; // int in Java
int *can_be_null = &can_never_be_null; // Integer in Java
*can_be_null = 0; // Integer.set or whatever
can_be_null = 0; // This is setting "the box" to null,
// NOT setting the integer value