How to check for empty array?

Hi


I am using the following code to do a DB lookup


NSArray *items = [[DataManager alloc] getItemInfoFromBarCode:symbol.data];


I am doing this inside a loop and feeding it different values as symbol.data


In each loop I need to know if I got a hit or not and if it filled the items array with data I need to break out of the loop and not feed it more data


My problem is I cannot figure out how to see if the array has been filled with data or not


Any hints would be very helpful


Matt

Accepted Reply

You can just do:

if (items.count)
    /* The array exists and has elements */;
else
    /* items is either nil or an empty array */;

Replies

You can just do:

if (items.count)
    /* The array exists and has elements */;
else
    /* items is either nil or an empty array */;

worked like a charm, thanks a lot

You may want to be a little careful - if the item does not exists (i.e. item==nil) then item.count may throw an exception. So in general, test if(item) first and then if(item.count>0) second.

No, that's not a problem. items is an object pointer. items.count is an access of one of its properties. It's equivalent to [items count]; that is, sending a message. It is not equivalent to dererencing a null pointer. Sending a message to nil is safe and returns 0/nil/false.

Sending a message to nil is safe …

Most of the time. Certainly it’s safe in this case, but you can run into trouble if the return result is a floating point number or a structure.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"