How to know if a Nsarray is empty (or void) using IF

Asked

Viewed 100 times

2

I need to know if a Nsarray is empty or void using an if.

Code:

NSArray* array;

 if( array == nil)
{ 
   // Fazer algo
}

2 answers

4


As in objective-c a message to nil returns nil, you can use the code below:

NSArray *array = [obtem o valor];
if ([array count]) {
    // Nao é vazio nem nulo
}

If the array is nil, then the result of [array count] will also be nil (what is considered "false" in the if). If it is not nil, then the method count returns the number of elements. If it is zero, if will not enter either, since zero is also considered false.

  • I found another solution... using NULL instead of nil!

  • Thanks @carlosfigueira, your answer is very good!!

  • To clarify better why use the ([array count]) in place of NULL has a very cool article at this Nshipster link

  • Great link!! Thank you! @iTsangar

1

Well, it was quicker than I thought.

I used NULL instead of Nil, staying this way:

NSArray* array;

 if( array == NULL)
{ 
   // Fazer algo
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.