35 tips for writing code specifications in iOS, 35 tips for writing code in ios

Source: Internet
Author: User

35 tips for writing code specifications in iOS, 35 tips for writing code in ios

1. streamline the code and return the value of the last sentence. This method has an advantage that all variables are in the code block, that is, they are only valid in the area of the code block, this means that the naming of other scopes can be reduced. However, the disadvantage is poor readability.

NSURL *url = ({ NSString *urlString = [NSString stringWithFormat:@"%@/%@", baseURLString, endpoint];

[NSURL URLWithString:urlString];

});

2. About compiler: Close warning:

#pragma clang diagnostic push

#pragma clang diagnostic ignored "-Warc-performSelector-leaks"

[myObj performSelector:mySelector withObject:name];

#pragma clang diagnostic pop

3. Ignore useless variables

# Pragma unused (foo)

Clearly define errors and warnings

# Error Whoa, buddy, you need to check for zero here!

# Warning Dude, don't compare floating point numbers like this!

4. Avoid circular references

  • If [block internal] uses [strong reference of external Declaration] to access [object A], [block internal] will automatically generate A [strong reference] pointing to [object]

  • If [block internal] uses [Weak reference of external Declaration] to access [object A], [block internal] will automatically generate A [Weak reference] pointing to [object]

__weak typeof(self) weakSelf = self;

dispatch_block_t block = ^{

   [weakSelf doSomething]; // weakSelf != nil

// preemption, weakSelf turned nil

[weakSelf doSomethingElse]; // weakSelf == nil

};

It is best to call it like this:

_ Weak typeof (self) weakSelf = self;

MyObj. myBlock = ^ {

_ Strong typeof (self) strongSelf = weakSelf;

If (strongSelf ){

[StrongSelf doSomething]; // strongSelf! = Nil

// Preemption, strongSelf still not nil (strongSelf is not nil during preemption)

[StrongSelf doSomethingElse]; // strongSelf! = Nil}

Else {// Probably nothing... return;

}

};

5. Macros must be written in uppercase, at least in uppercase, and all in lowercase. Sometimes no parameters are prompted;

6. It is recommended to write enumerative to imitate apple-an enumerated data type NSUInteger is bound while listing the enumerated content. The advantage of this is enhanced type check and better code readability. Example:

// Not recommended

Typedef enum {

UIControlStateNormal = 0,

UIControlStateHighlighted = 1 <0,

UIControlStateDisabled = 1 <1,

} UIControlState;

// Recommended statement

Typedef NS_OPTIONS (NSUInteger, UIControlState ){

UIControlStateNormal = 0,

UIControlStateHighlighted = 1 <0,

UIControlStateDisabled = 1 <1,

};

7. We recommend that you load xib and use NSStringFromClass () as the xib name to avoid writing errors.

// Recommended statement

[Self. tableView registerNib: [UINib nibWithNibName: NSStringFromClass ([DXRecommendTagVCell class]) bundle: nil] forCellReuseIdentifier: ID];

// Not recommended

[Self. tableView registerNib: [UINib nibWithNibName: @ "DXRecommendTagVCell" bundle: nil] forCellReuseIdentifier: ID];

8. scenario requirement: in inheritance, any method that requires the subclass to override the parent class must first call this method of the parent class for initialization. It is recommended that NS_REQUIRES_SUPER be added after the method name of the parent class; when the subclass overrides this method, it will automatically warn you to call this super method, sample code

// Note: If 'ns _ REQUIRES_SUPER 'is added to the method in the parent class, a warning is prompted only when the subclass is overwritten.

-(Void) prepare NS_REQUIRES_SUPER;

9. It is recommended that you do not write the attribute name like the system to avoid inexplicable problems. Note label and do not write the attribute name as textLabel.

10. Add a plist file to the project. The file name is info. plist to prevent the file name from being duplicate with that of the system;

11. If the controller has been loaded, it does not need to be loaded again to optimize performance.

if (vc.isViewLoaded) return;

12. The id type attribute cannot use the dot syntax. The get method can only be called in brackets. The [id method name] can be called using the new generic feature of iOS9, such as arrays;

@property (nonatomic,strong) NSMutableArray *topicsM;

13. If it is not an attribute, try not to use the syntax. It is recommended by an old programmer;

14. If you use a third-party framework, try not to change the internal files. Instead, you should encapsulate the files again and customize the files;

15. Determine if writing mode

We recommend that you write this code.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

    if (indexPath.row == 0) return 44;

    if (indexPath.row == 1) return 80;

    if (indexPath.row == 2) return 50;

    return 44;

}

Instead

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

    if (indexPath.row == 0) {

        return 44;

    }else if (indexPath.row == 1){

        return 80;

    }else if (indexPath.row == 2){

        return 50;

    }else{

        return 44;

    }

}

16. Take over a new project, perform quick debugging, view the role of a module or method, comment out a method or code block, and directly write return; instead of Selecting All, comment out;

For example, check the function of loadNewRecommendTags.

-(Void) loadNewRecommendTags

{

Return;

 

[SVProgressHUD show];

// Cancel the previous Task

[Self. manager. tasks makeObjectsPerformSelector: @ selector (cancel)];

NSMutableDictionary * params = [NSMutableDictionary dictionary];

 

Params [@ "a"] = @ "tag_recommend ";

Params [@ "c"] = @ "topic ";

Params [@ "action"] = @ "sub ";

[Self. manager GET: DXCommonUrlPath parameters: params success: ^ (NSURLSessionDataTask * _ Nonnull task, id _ Nonnull responseObject ){

 

Self. recommendTag = [DXRecommendTag mj_objectArrayWithKeyValuesArray: responseObject];

[Self. tableView reloadData];

[SVProgressHUD dismiss];

} Failure: ^ (NSURLSessionDataTask * _ Nullable task, NSError * _ Nonnull error ){

DXLog (@ "% @", error );

[SVProgressHUD dismiss];

}];

}

17. In a custom View or cell, modal provides a controller suggestion:

[UIApplication sharedApplication].keyWindow.rootViewController

Replace

Self. window. rootViewController, because the program may have more than one window, self. window may not be the main window;

18. Suggestion: Use CGSizeZero instead of CGSizeMake );

CGRectZero replaces CGRectMake (0, 0, 0, 0 );

CGPointZero instead of CGPointMake (0, 0)

19. Suggestions for listening to the keyboard:

UIKIT_EXTERN NSString *const UIKeyboardWillChangeFrameNotification

Instead, the following code. Because the keyboard may change the input method, convert it to emoticon input, and switch it to English, the frame may become high or short, and may not necessarily send the following notifications, but the above notification will certainly be sent.

UIKIT_EXTERN?NSString *const UIKeyboardWillShowNotification;

UIKIT_EXTERN?NSString *const UIKeyboardDidShowNotification;

UIKIT_EXTERN?NSString *const UIKeyboardWillHideNotification;

UIKIT_EXTERN?NSString *const UIKeyboardDidHideNotification;

20. the String constant specification for releasing notifications. It is recommended to imitate apple. The text of the notifications on the above keyboard, coupled with const, ensures that the string cannot be changed and ends with Notification. At first glance, you will know that it is a Notification; make sure that the sentence is too long;

NSString *const buttonDidClickNotification = @"buttonDidClickNotification";

21. if the divisor is 0, an error will be reported directly below ios8. (NaN-> Not a Number) iOS9 won't. Therefore, we should make a judgment. For example, if the server returns the width and height of the image and scales proportionally, CGFloat contentH = textW * self. height/self. width;

22. If the declared attribute only uses the get method, does not use the set method, and does not want the outside world to change the value of this attribute, it is recommended to add readonly in brackets. Example:

@property(nonatomic,readonly,getter=isKeyWindow) BOOL keyWindow;

23. If the attribute is of the BOOL type, we recommend that you rewrite the get method name in parentheses to improve readability. The sample code is as follows;

24. before getting a photo from the system album, you should determine whether the system album is available. If you take a photo from the camera, you must determine whether the camera is available.

// Determine whether the album can be opened

If (! [UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary]) return;

 

// Determine whether the camera can be opened

If (! [UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) return;

25. in navigation control, or its sub-controller, set the title of the navigation bar to use self. navigationItem. title = @ "title" instead of self. title = @ "title ";

26. setFrame is recommended for setting the split line for the cell: Set the split line by setting its height, instead of adding a high UIView to the bottom of the cell. In this way, a control is added, in terms of performance, it is better to use setFrame to set the height.

27. A large number of layers may cause applications to become very stuck and poor user experience. Therefore, do not operate layers as much as possible. For example, set button rounded corners, or set rounded corners for buttons;

self.loginBtn.layer.cornerRadius = 5;

self.loginBtn.layer.masksToBounds = YES;

28. we recommend that you add a prefix to the classification extension method, such as the Third-party framework SDWebImage. This method is easily separated from the system method, reducing the communication cost between programmers, similarly, when adding attributes to a category (using runtime), we recommend that you add a prefix to prevent apple from adding identical attribute names over a period of time. For example, you have added the placeholderColor attribute to the UITextField category, if one day the company officially added this identical name attribute to placeholder, it would not be good.

29. when a color is added to a control in storyboard or xib, the color diagonal line has a split line, indicating that transparency can be set. If transparency is set for this control, we recommend that you set it here instead of alpha, if alpha is set, the text above will become unclear as the transparency increases. You can set background --> other --> opacity

30. it is not recommended to write a/B 1.0 as the integer type to the floating point type. This is an incorrect writing method, for example, 1.5/2 1.0. According to the algorithm, from the right to the right, 0 1.0 = 0, write 1.0 1.5/2 in front of it. We recommend that you convert it directly. (double) a/B;

31. The extraction method, or writing tool class, can write class methods, and try to write class methods as much as possible, reducing the steps for creating objects, such as loading xib and viewWithXib for the extended class of UIView;

32. Time-consuming operations should be placed in sub-threads to prevent the main thread from getting stuck, such as calculating the file size, downloading large files, and clearing the cache;

33. declare an attribute. If it is an object, such as an array, it cannot start with the new word. Otherwise, an error is reported because new is a method for generating an object in OC, which has special meanings. For example,

@property (nonatomic,strong) NSMutableArray *newTopicsM;

NOTE: If newtopicsM is a word (different from the camper mark), no error will be reported for writing. If it is a basic data type, no error will be reported, for example

@property (nonatomic,assign) int newNumber;

However, if you must write the attribute starting with the new word, when declaring the attribute, rewrite the getter method name, but note the following when using the getter method:

34. In the custom method, the use of and should be retained. It should not be used to describe multiple parameters, just like the following example of initWithWidth: height:

- (instancetype)initWithWidth:(CGFloat)width height:(CGFloat)height;

Instead

- (instancetype)initWithWidth:(CGFloat)width andHeight:(CGFloat)height;

35. It is recommended that you write the parameter Dictionary of the POST request ~

// NSDictionaryOfVariableBindings generates a Dictionary. This macro can generate a Dictionary map from the variable name to the variable value, for example:

NSNumber * packId = @ (2 );

NSNumber * userId = @ (22 );

NSNumber * proxyType = @ (2 );

NSDictionary * param = NSDictionaryOfVariableBindings (packId, userId, proxyType );

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.