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)明确定义错误和警告#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"
__WeaktypeofSelf) weakself =self;dispatch_block_t block = ^{[weakself dosomething];//weakself! = Nil//preemption, Weakself turned nil[weakSelf Dosomethingelse]; //weakself = nil}; Better 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:
// 不推荐写法typedef enum{ UIControlStateNormal = 0, UIControlStateHighlighted = 1 << 0, UIControlStateDisabled = 1 << 1,} UIControlState;
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
// 推荐写法 [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([DXRecommendTagVCell class]) bundle:nil] forCellReuseIdentifier:ID];
// 不推荐写法 [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
// 注意:父类中的方法加`NS_REQUIRES_SUPER`,子类重写才有警告提示- (void)prepare NS_REQUIRES_SUPER;
9. It is suggested that the write attribute name should not be the same as the system, avoid the problem of inexplicable; Pay special attention to the label; attribute names are not writtentextLabel
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<DXTopics *> *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) { Span class= "Hljs-keyword" >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, you need to comment out a method, or a block of code, directly write return;
rather than select all, comment out;
For example: See how this method loadNewRecommendTags
works
- (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 in a custom cell, modal out a controller recommendation:
[UIApplication sharedApplication].keyWindow.rootViewController
Replace
self.window.rootViewController,因为程序可能不止一个window,self.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;
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
// 判断相册是否可以打开if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) return;// 判断相机是否可以打开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, the same as the classification to add attributes (using the runtime), the proposed prefix, to prevent Apple official over time to add the same property name, For example, the Uitextfield category added placeholdercolor This attribute, in case the official to placeholder extension of 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, this is the wrong way to write, 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; (Dou BLE) 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<DXTopics *> *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 and
usage of the word 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;而不应该- (instancetype)initWithWidth:(CGFloat)width andHeight:(CGFloat)height;
35. Recommend the POST request parameter dictionary writing, so compare loading force ~
// NSDictionaryOfVariableBindings这个宏生成一个字典,这个宏可以生成一个变量名到变量值映射的Dictionary,比如:NSNumber * [email protected](2);NSNumber *[email protected](22);NSNumber *[email protected](2);NSDictionary *param=NSDictionaryOfVariableBindings(packId,userId,proxyType);
Writing code specifications in iOS