35 Tips for writing code specifications in iOS

Source: Internet
Author: User
Tags set background

1. Streamline the code and return the value of the last sentence, this method has one advantage, all the variables in the code block, that is, only in the area of the code block, which means that you can reduce the naming pollution of other scopes. But the disadvantage is that the readability is poor

Nsurl *url = ({nsstring *urlstring = [NSString stringwithformat:@ "%@/%@", baseurlstring, endpoint];

[Nsurl urlwithstring:urlstring];

});

2. About the compiler: Turn off the warning:

#pragma clang diagnostic push

#pragma clang diagnostic ignored "-warc-performselector-leaks"

[MYOBJ Performselector:myselector Withobject:name];

#pragma clang diagnostic pop

3. Ignore the unused variables

#pragma unused (foo)

Explicitly 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" accesses "object a" using "strongly referenced externally declared", then "block internal" automatically produces a "strong reference" to "object A"

    • If "block internal" accesses "object a" using "weakly referenced externally", then "block internal" automatically produces a "weak reference" pointing to "object a"

__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 this:

__weak typeof (self) weakself = self;

Myobj.myblock = ^{

__strong typeof (self) strongself = weakself;

if (strongself) {

[Strongself dosomething]; Strongself! = Nil

Preemption, Strongself still not nil (at the time of preemption, strongself or non-nil)

[Strongself Dosomethingelse]; Strongself! = nil}

else {//Probably nothing ... return;

}

};

5. Macro should be written in uppercase, at least uppercase, all lowercase sometimes write without prompting parameters;

6. It is recommended to write enumerations to mimic apples--binding enumerated data type Nsuinteger while enumerating content is listed, which benefits from enhanced type checking and better code readability, for example:

No recommended wording

typedef enum{

UIControlStateNormal = 0,

uicontrolstatehighlighted = 1 << 0,

uicontrolstatedisabled = 1 << 1,

} uicontrolstate;

Recommended wording

typedef ns_options (Nsuinteger, uicontrolstate) {

UIControlStateNormal = 0,

uicontrolstatehighlighted = 1 << 0,

uicontrolstatedisabled = 1 << 1,

};

7. It is recommended to load Xib,xib name with Nsstringfromclass () to avoid writing errors

Recommended wording

[Self.tableview registernib:[uinib Nibwithnibname:nsstringfromclass ([Dxrecommendtagvcell class]) Bundle:nil] Forcellreuseidentifier:id];

No recommended wording

[Self.tableview registernib:[uinib nibwithnibname:@ "Dxrecommendtagvcell" Bundle:nil] forCellReuseIdentifier:ID];

8. Scenario requirements: In inheritance, a method that requires subclasses to override the parent class must first call the parent class's method for initialization; Recommendation: The method name of the parent class is appended with Ns_requires_super; Subclasses overriding this method will automatically warn you to call this super method, the sample code

Note: The method in the parent class is added ' Ns_requires_super ', and the subclass overrides have a warning prompt

-(void) prepare ns_requires_super;

9. It is suggested that the write attribute name should not be the same as the system, to avoid the problem of inexplicable; Pay special attention to the label; attribute names do not write Textlabel

10. Add the plist type file to the project, do not name info.plist, to prevent and the system comes with the file names, the problem occurs inexplicably;

11. If the controller has been loaded, do not load again, optimize performance

if (vc.isviewloaded) return;

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

@property (Nonatomic,strong) Nsmutablearray *TOPICSM;

13. If not the attribute, try not to point grammar, an old programmer's advice;

14. Use the third-party framework, try not to change the internal files, but should be encapsulated, personalized customization;

15. Judging if Writing method

It is recommended to write

-(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 of

-(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, quickly debug, see the role of a module or method, need to comment out a method, or a block of code, directly write return, rather than select all, comment out;

For example: View this method Loadnewrecommendtags effect

-(void) loadnewrecommendtags

{

Return

[Svprogresshud show];

Cancel a 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 in a custom cell, modal out a controller recommendation:

[UIApplication Sharedapplication].keywindow.rootviewcontroller

Replace

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

18. Recommendation: Replace Cgsizemake (0,0) with Cgsizezero;

Cgrectzero replaces CGRectMake (0, 0, 0, 0);

Cgpointzero instead of Cgpointmake (0, 0)

19. Notification suggestions for monitoring the keyboard:

Uikit_extern NSString *const uikeyboardwillchangeframenotification

Instead, the following code, because the keyboard may change the input method, switch to the expression input, switch to English, then frame may become taller, become shorter, do not necessarily send the following notice, but will certainly send the above notice

Uikit_extern? NSString *const uikeyboardwillshownotification;

Uikit_extern? NSString *const uikeyboarddidshownotification;

Uikit_extern? NSString *const uikeyboardwillhidenotification;

Uikit_extern? NSString *const uikeyboarddidhidenotification;

20. The specification of the string constants for the publication of notifications, it is recommended to imitate apples; if the writing of the notification on the keyboard, plus the const guarantee string can not be changed, to notification end, a look is informed, should try to ensure readability, do not fear that the sentence is too long;

NSString *const buttondidclicknotification = @ "Buttondidclicknotification";

21. If the divisor is 0,ios8 below will be directly error, (Nan->not a number) iOS9 will not, so should be judged, such as the server returns the width of the picture, proportionally scaled, cgfloat contenth = TEXTW * Self.height/ Self.width;

22. If you declare a property, you only want to use the Get method, do not use the Set method, and do not want the outside world to change the value of this property, it is recommended to add ReadOnly in parentheses; Example:

@property (Nonatomic,readonly,getter=iskeywindow) BOOL Keywindow;

23. If the attribute is of type bool, it is recommended to override the Get method name in parentheses to improve readability, as shown in the example code above;

24. Before taking a photo from the system album, you should determine if the system album is available, and if you take a picture from the camera, determine if the camera is available

Determine if the album can be opened

if (![ Uiimagepickercontroller Issourcetypeavailable:uiimagepickercontrollersourcetypephotolibrary]) return;

Determine if the camera can be opened

if (![ Uiimagepickercontroller Issourcetypeavailable:uiimagepickercontrollersourcetypecamera]) return;

25. In the navigation control, or its sub-controller, set the title of the navigation bar should be used Self.navigationItem.title = @ "title" and not recommended Self.title = @ "title";

26. To set the cell division line, it is recommended to use Setframe: by setting it height, set the split line, but not recommended to the cell bottom to add a height of uiview, this adds a control, in terms of performance, rather than using setframe to set the height

27. A large number of operation layers may cause the application is very card, to the user experience is poor, so try not to manipulate the layer, such as setting the button fillet, such as the setting of a corner buttons;

Self.loginBtn.layer.cornerRadius = 5;

Self.loginBtn.layer.masksToBounds = YES;

28. For the classification extension method, it is recommended to prefix, such as the third-party framework Sdwebimage, so that the system is easy to separate the method, reduce the cost of communication between programmers, with the same classification to add attributes (using runtime), the proposed prefix, To prevent Apple official over time to add the same property name, such as to the Uitextfield category added placeholdercolor This attribute, in case the official to placeholder extended the name of the same attribute, then it is not good

29. Usually in storyboard or xib to add a color to a control, the color diagonal has a split line, indicating that you can set the transparency, if you set the transparency of the control is set here, rather than set alpha, because Alpha is set, then the text will be larger with transparency , and become unclear; you can set background-->other-->opacity

30. Shaping into floating-point type, not recommended to write A/b 1.0, so write is the wrong way of writing, example 1.5/2 1.0, according to the algorithm, from the right, 0 1.0 = 0, but should be written in front 1.0 1.5/2; (double) A/b;

31. The extraction method, or write the tool class, can write the class method, as far as possible writes the class method, reduces the creation object The step, for example to UIView expands the classification to load the xib,viewwithxib;

32. Time-consuming operation should be placed on the sub-thread, avoid the main thread of the card, such as calculate file size, download large files, clear the cache;

33. Declare a property, if it is an object, such as an array, cannot start with the new word, or directly error, because new in OC is the method of generating an object, has a special meaning;

@property (Nonatomic,strong) Nsmutablearray *NEWTOPICSM;

Note: If NEWTOPICSM is a word (different from the hump flag), this will not be an error, and if it is a basic data type it will not be an error, such as

@property (nonatomic,assign) int newnumber;

However, if you must write a property that begins with the new word, then when declaring the property, overriding the getter method name only takes care of using the Getter method.

34. In the custom method, the usage of the word "and" should be preserved. It should not be used for multiple parameters to illustrate, just like the following example of Initwithwidth:height:

-(Instancetype) Initwithwidth: (cgfloat) Width height: (cgfloat) height;

and should not

-(Instancetype) Initwithwidth: (cgfloat) Width andheight: (cgfloat) height;

35. Recommend the POST request parameter dictionary writing, so compare loading force ~

Nsdictionaryofvariablebindings this macro into a dictionary that can generate a variable name to the dictionary of a variable value map, such as:

NSNumber * [email protected] (2);

NSNumber *[email protected] (22);

NSNumber *[email protected] (2);

Nsdictionary *param=nsdictionaryofvariablebindings (Packid,userid,proxytype);

35 Tips for writing code specifications in iOS

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.