It is not necessary to assign nil as the initial value to the variable
NSString *mystring = nil;
The above code is the same as the nil effect, so let's keep it simple:
NSString *mystring;
The same is true for property handling. Remember that nil is equivalent to 0, and the latter is equivalent to a Boolean no, so it does not need to be as follows:
@property (nonatomic, assign) BOOL didLoad;
...
didLoad = NO;
It is not necessary to set the initial value to no, because the initial value of all variables is nil, so the value of Didload is No.
Delegate (Delegate)
if
(self.delegate) {
if
([self.delegate respondsToSelector:@selector(@
"didFinish"
)]) {
[self.delegate didFinish];
}
}
This code can also be simplified, when delegate is nil, nil can only receive messages with a value of nil, so the outer layer of judgment is unnecessary and can be simplified as follows:
if
([self.delegate respondsToSelector:@selector(@
"didFinish"
)]) {
[self.delegate didFinish];
}
Simplified conditional clauses
if
(myObj == nil)
Can be simplified to:
if
(!myObj)
Also be careful to avoid using! =:
if
(myObj != nil)
It's hard to read and see how simple the following features are:
if
(myObj)
A string of objects can also be nil
if
(a.b.c)
The above code when any of a, B, C is nil, the value is false, so it is completely OK, so there is no need to write the following:
if
(a)
if
(a.b)
if
(a.b.c)
To keep nil for nil.
I've noticed that I've written a lot of this code before: Initialize an array to an empty array @[] Instead of keeping the array in nil or uninitialized state. But actually keeping them nil is no good. If you have an array object with a value of nil, you check the number of it, and check the number of empty arrays as a result. In the code below, whether myarray is nil or @[], the result of the conditional judgment is true.
if
(myArray.count == 0)
Best practices for nil use in objective-c