views:

752

answers:

4

SO I wish to check to see if the item in my array [clientDataArray objectForKey:@"ClientCompany"] is nil.

    temp = [clientDataArray objectForKey:@"ClientCompany"];
    if (temp != [NSNull null]) infofieldCompany.text = temp;

So far I have been able to achieve this through the above code, but it does give me the warnings

  • warning: 'NSArray' may not respond to'-objectForKey:'
  • warning: comparison of distinct Objective-C types 'struct NSNull *' and 'struct NSString *' lacks a cast

My main interest is the second warning, but the first warning also interest me. How should I adapt my above code?

+4  A: 

Your first warning looks like you're trying to call objectForKey on an NSArray. Which isn't going to work, as NSArray doesn't have an objectForKey method.

As for the second warning you can just compare directly with nil, ie:

if (temp != nil)

or since nil is equivalent to 0, you can also just do:

if (temp)
Tom
yeah, I should have done that. Nice and simple too.The first line i posted does indeed work fine, but I will have a rethink of it.
norskben
A: 

I think the problem is (I mean the second warning) is that you're comparing NSString object, which could be set to null to an NSNull object.

Have you tried the usual C way of checking for null?

if(temp) {
// It's not null, do something.
}

I'm not 100% sure about this one, but you could try it. If you did, sorry that couldn't provide more useful information.

Good luck!

Ziggy
+4  A: 

Both of the answers previously given missed a fundamental point: you can't put nil into an array, so you'll never get nil out of an array. Using NSNull as a placeholder in an array is the correct thing to do, however your variable temp then cannot be declared as an NSString *, as it might not be one. Use either NSObject * or id as the type of the variable to suppress the comparison warning.

Graham Lee
A: 

The NSNull singleton can be used to build "interleaved" arrays like obj0, obj1, obj2, NSNull, obj3, NSNull, ..., nil.

warning: 'NSArray' may not respond to'-objectForKey:'

NSArray does not implement objectForKey.
Your code will crash at runtime (if clientDataArray has been allocated and initialized) You can access array elements by index (objectAtIndex:).
If you need to associate objects with keys, take a look at NSDictionary.

weichsel