Best practices for nil use in Objective-c

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.