user2408952
user2408952

Reputation: 2041

How to see if NSArray, created with valueForKey is empty

I got an array:

NSArray *itemsArray = [self.tournamentDetails.groups valueForKey:@"Items"];

Where self.tournamentDetails.groups is an NSArray, build with a JSON string from a webRequest.

Items is sometimes empty and sometimes it contains objects. So i need an if statement to check if its empty or not. I've tried some different things like:

if ([itemsArray count]!=0)
if (!itemsArray || !itemsArray.count)

Problem is that if my Items object from valueForKey is empty then the itemsArray still contains an object looking like this

<__NSArrayI 0x178abef0>(
<__NSArrayI 0x16618c30>(

)

)

When theres items inside my Items object it looks like this:

<__NSArrayI 0x18262b70>(
<__NSCFArray 0x181e3a40>(
{
    BirthDate = 19601006T000000;
    ClubName = "Silkeborg Ry Golfklub";
    ClubShortName = "";
    CompletedResultSum =     {
        Actual =         {
            Text = 36;
            Value = 36;
        };
        ToPar =         {
            Text = "";
            Value = 0;
        };
    };
}
)
)

Meaning that [itemsArray count] is always equal to 1 or more, and then it jumps into the if statement when it should not.

Anyone know how i can create an if statement where if itemsArray contains "Items:[]" it will be skipped and if itemsArray contains "Items:[lots of objects]" it will run?

EDIT: Solution is to check up on the first index like this if([[itemsArray objectAtIndex:0] count] != 0) then run code.

Upvotes: 0

Views: 676

Answers (2)

hariszaman
hariszaman

Reputation: 8424

more simpler

  for (id obj in itemsArray)
  {
      if([obj isKindOfClass:[NSArray class]])
      {
          if(obj.count > 0)
          {
             //your if condition here 
          }
      }
  }

Upvotes: 0

nmh
nmh

Reputation: 2503

Try this:

if(itemsArray && itemsArray.count>0) //be sure that it has value){
   for(NSArray *item in itemsArray){
       if(item.count > 0){
           // you have an NSDictionary. Will process it 
       }else{
           //item.count == 0 : this is an empty NSArray.
       }
   }
}

Upvotes: 1

Related Questions