How to check if an array is empty or empty?

I want to check if my array or zero is empty, and based on which I want to create a condition, for example.

if(array == EMPTY){ //do something } 

Hope I understand what I'm asking, just need to check if my array is empty?

considers

+55
objective-c iphone
Oct 18 2018-10-18
source share
12 answers
 if (!array || !array.count){ ... } 

This checks if the array is nil, and if not, check if it is empty.

+107
Oct 18 2018-10-18
source share
 if ([array count] == 0) 

If the array is nil, it will also be 0, since nil displays 0; therefore, checking whether an array exists is not required.

In addition, you should not use array.count as suggested. This may work, but it is not a property, and will list everyone who reads your code nuts if they know the difference between the property and the method.

UPDATE: Yes, I know that years later the account is now officially owned.

+27
Oct. 18 '10 at 19:28
source share

you can try like this

 if ([array count] == 0) 
+10
Oct 18 2018-10-18
source share

Just to be really verbose :)

 if (array == nil || array.count == 0) 
+7
Oct 18 '10 at 13:05
source share

The best performance.

 if (array.firstObject == nil) { // The array is empty } 

The way to work with large arrays.

+5
Dec 04 '14 at 5:59
source share
 if (array == (id)[NSNull null] || [array count] == 0) { NSLog(@"array is empty"); } 
+4
Jan 03 '13 at 7:56
source share

Since nil displays 0, which is NO , the most elegant way should be

 if (![array count]) 

The operator '==' is not needed.

+2
Jan 03 '13 at 7:45
source share

You can also perform such a test using if (nrow> 0). If your data object is not formally an array, it might work better.

+1
May 9 '13 at 9:05
source share

null and empty are not the same, I suggest you treat them differently

 if (array == [NSNull null]) { NSLog(@"It null"); } else if (array == nil || [array count] == 0) { NSLog(@"It empty"); } 
+1
May 9 '13 at 9:37
source share

Swift 3

As in the latest version of swift 3, the option to compare s> and <options is not available

You can still compare options with the == symbol, so the best way to check if the extra array contains values ​​is:

 if array?.isEmpty == false { print("There are objects!") } 

by the number of arrays

 if array?.count ?? 0 > 0 { print("There are objects!") } 

There are other ways and can be checked here link to answer

+1
Mar 08 '17 at 6:07
source share
 if (array == nil || array.count == 0 || [array isEqaul [NSNull Null]]) 
0
Apr 18 '17 at 8:52
source share

In Swift 4

 if (array.isEmpty) { print("Array is empty") } else{ print("Array is not empty") } 
0
Dec 05 '18 at 7:49
source share



All Articles