This article focuses on the question of whether or not to be aware of Nsarray.
Some inexperienced developers, when judging whether an array is empty, will simply write:
if (array! = nil)
This form, or:
if (Array.count! = 0)
This form.
In fact, strictly speaking, both of these formulations are considered insufficient and unstable.
First of all, the difference between the two.
Array = = Nil
This is the case when the array object is a nil object, not an Nsarray type object. Any direct call to the Nsarray class property will cause the program to crash, for example:
int length = Array.count; If the array is a nil object, the program will go to this line directly crash
Array.count = = 0
This is different from the fact that the array at this point is a Nsarray type object, except that there are no elements in the array. But it can be used as a Nsarray object in itself.
int length = Array.count; There is no problem, the value of length is 0
But why is it not safe to say either of these judgments?
The reason is that both of these situations are likely to occur in real-world development.
In the former case, the background may be due to a variety of reasons, the return of a null value for a field, then we take the nil, the latter case, the background may be a value for a certain data, but taken to 0, then returned is an empty group, we take the [], empty group.
A big part of our short value judgment is that the program guarantees stability when the backend interface data returns some anomalous data.
Therefore, it is not safe to judge a situation, and it needs to be judged in both cases.
For example, you can write:
if (array! = Nil && Array.count! = 0)
And my personal advice is that when judging array.count, it's best not to use it. , although in the above code, Array.count will not have problems, but as a habit, I would recommend to write:
if (array = nil && [array count]! = 0)
The reason is simple, [array count] does not cause crash to appear even when the array is a nil object.
In iOS development, the array is empty judgment processing