iOS Development Specifications & Recommendations

Source: Internet
Author: User

IOS Development Specifications & Recommendations

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 defines 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"

typeof (self) weakself == ^//  weakself! = Nil//  preemption, Weakself turned Nil//  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 (when 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 enum  0 1 0 1 1,} uicontrolstate;
// recommended Wording  0 1 0 1 1,};

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

// recommended Wording 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 adds ' Ns_requires_super ', and the subclass rewrite has a warning hint -(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 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 it is not a property, try not to point the syntax; using dot syntax makes the code concise. In other cases, however, you should use the square bracket syntax.

// Recommended Nsinteger Arraycount == [Uicolor orangecolor];[ UIApplication Sharedapplication]. delegate;
// Not recommended Nsinteger Arraycount = self.array.count;[ View Setbackgroundcolor:[uicolor Orangecolor]; Uiapplication.sharedapplication. delegate;

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

15. Judging if Writing method

suggested write -(cgfloat) TableView: (UITableView *) TableView Heightforrowatindexpath: (Nsindexpath *) indexpath{  if0returnto; if 1 return  the ; if 2 return  - ; return  - ;}

Instead of

-(CGFloat) TableView: (UITableView *) TableView Heightforrowatindexpath: (Nsindexpath *) indexpath{if(Indexpath.row = =0) {return  -;}Else if(Indexpath.row = =1){return  the;}Else if(Indexpath.row = =2){return  -;}Else{return  -;}}

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:paramssuccess:^ (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 instead of Self.window.rootViewController because the program may have more than one window , Self.window may not be the main window;

18. Recommendations:

Replace Cgsizemake with Cgsizezero (0,0); Cgrectzero instead of CGRectMake (0000); Cgpointzero instead of Cgpointmake (00)

19. Notification suggestions for monitoring the keyboard:

Uikit_extern NSString *const  uikeyboardwillchangeframenotification instead of, the following code; Because the keyboard may change the input method, switch to the expression input, Switch to English, then the frame may become taller and shorter, 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";

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, scaled proportionally:

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 return ; // determine if the camera can be opened if return;

25. In the navigation control, or its sub-controller, set the title of the navigation bar should be used

Self.navigationItem.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;

5= 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. Plastic conversion to floating point, not recommended to write A/b * 1.0, so write is wrong, example 1/2 * 1.0; According to the algorithm, from left to right, 0 * 1.0 = = 0, but should be written in front 1.0 * 1/2; Direct strong (double) A/b is recommended;

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 *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; instead of -(Instancetype) Initwithwidth: ( CGFloat) Width andheight: (cgfloat) height;

35. Crash caused by multi-threaded synchronization problem
For a data source or model class, it is important to note the simultaneous access of multiple threads, which can be synchronized with GCD's serial queue.

Removal of 36.Observer
Many of the current code needs to use observer, depending on the state of the object being observed to update the UI or perform an operation. Registering observer is simple, but when you remove it, it's a problem, either by forgetting to remove the observer, or by removing the wrong time. If a observed object has been released, observer is still there, and the result can only be crash, so remember to remove at least DEALLOC inside Observer

37.NSArray, nsdictionary Protection of members
In AddObject or InsertObject to Nsarray or nsdictionary, it is best to add a space protection, especially network-related logic, if the network returned to empty (Jason parse out empty), you need to first empty and add to the array inside

38.commit code before you must ensure that there is no warning, no memory leaks, ensure that all OK and then upload the code. Before uploading the code command + Shift + b static analysis to see if there is any issue can

iOS Development Specifications & Recommendations

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.