Processing of null array judgment in iOS development
This article focuses on the issues that need attention when NSArray determines whether it is null.
When determining whether the array is null, some developers write it:
if (array != nil)
Or:
if (array.count != 0)
Strictly speaking, these two methods are both inefficient and unstable, and ignore a more common situation.
First, the difference between the two.
Array = nil
In this case, the array object is an nil object, not an NSArray object. The nil object is an object that can receive any message. It can be assigned to any object. It is no problem for you to send messages to it, even though you cannot get the desired result.
Array. count = 0
In this case, the array is an NSArray object, but there is no element in this array. But it can be used as an NSArray object.
In fact, if you are processing network request data, it is almost impossible (at least I have never met) to retrieve an array that is a nil object ), in most cases, there is another situation:
The obtained array is an NSNull object.
NSNull is a special class, which is the same as nil and also represents a null value. But there is a difference between the two. NSNull does not accept NSArray's methods. It has only one class method:
+ (NSNull *)null;
Therefore, sending NSArray-specific method or attribute access will cause program crash.
A major part of the null value judgment is to ensure the stability of the program when the background interface data returns some abnormal data.
For example, in some cases, the background may return a null value for a field for various reasons. In this case, we get an object such as [NSNull null]. For example, the backend may have a value for a certain data, but 0 is returned. In this case, an empty group is returned. what we get is @ [], an empty group.
Therefore, to determine whether the array is null, You need to determine all situations.
There are many writing methods, such as writing:
if (array != nil && ![array isKindOfClass:[NSNull class]] && array.count != 0)
If something is wrong, please correct it.