How to check if array is null or empty?

前端 未结 12 1389
后悔当初
后悔当初 2021-01-31 07:32

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

if(array ==  EMPTY){
//do something
}
相关标签:
12条回答
  • 2021-01-31 07:58

    null and empty are not the same things , i suggest you treat them in differently

    if (array == [NSNull null]) {
        NSLog(@"It's null");
    } else if (array == nil || [array count] == 0) {
         NSLog(@"It's empty");
    }
    
    0 讨论(0)
  • 2021-01-31 08:01

    In Swift 4

    if (array.isEmpty) {
        print("Array is empty")
    }
    else{
        print("Array is not empty")
    }
    
    0 讨论(0)
  • 2021-01-31 08:06

    You can also do this kind of test using if (nrow>0). If your data object is not formally an array, it may work better.

    0 讨论(0)
  • 2021-01-31 08:08
    if (array == nil || array.count == 0 || [array isEqaul [NSNull Null]])
    
    0 讨论(0)
  • 2021-01-31 08:09

    you can try like this

    if ([array count] == 0)
    
    0 讨论(0)
  • 2021-01-31 08:11
    if ([array count] == 0)
    

    If the array is nil, it will be 0 as well, as nil maps to 0; therefore checking whether the array exists is unnecessary.

    Also, you shouldn't use array.count as some suggested. It may -work-, but it's not a property, and will drive anyone who reads your code nuts if they know the difference between a property and a method.

    UPDATE: Yes, I'm aware that years later, count is now officially a property.

    0 讨论(0)
提交回复
热议问题