Some code suggestions for writing statements and variables in OBJECTIVE-C programming _ios

Source: Internet
Author: User
Tags error handling


Statement
Conditional statement



The conditional statement body should always be surrounded by curly braces. Only one line of code is best added, otherwise it will bring security risks.


 code as follows:

Recommended
if (!error) {
return success;
}


Not recommended
if (!error)
return success;

if (!error) return success;


Yoda expression (Yoda)





Do not use the Yoda expression. (the name originated in Star Wars, the Master of the speech way, always with flip-word order)


 code as follows:

Recommended
if ([myvalue isequal:@42]) {...


Not recommended
if ([@42 Isequal:myvalue]) {...


Inspection of NIL and bool





Some people like to check nil in this way:


code as follows:

if (nil = = myvalue) {...

This can avoid a less "=" error, because once the less write a "=", then nil can not be assigned, the compiler will report an error.





However, as mentioned earlier, it is best not to use the Yoda expression. So the better solution is to use the "!" To complete the inspection of nil and bool.


 code as follows:

Recommended
if (someobject) {...
if (![ Someobject Boolvalue]) {...
if (!someobject) {...


Not recommended
if (Someobject = YES) {...//Wrong
if (Myrawvalue = YES) {...//Never do.
if ([someobject boolvalue] = = NO) {...


do not nest multiple if statements





Instead of nesting multiple if statements, use multiple return to avoid adding complexity and improve code readability.



That is, in a method, the important part should not be placed in the IF statement, but instead put "other cases" in the IF.


 code as follows:

Recommended
-(void) SomeMethod {
if (![ Someother Boolvalue]) {
Return
}


Do something important
}

Not recommended
-(void) SomeMethod {
if ([Someother boolvalue]) {
Do something important
}
}


Complex Expressions





When a judgment condition is complex, they should be extracted and assigned to a bool variable.


 code as follows:

BOOL namecontainsswift = [sessionname containsstring:@ "Swift"];
BOOL iscurrentyear = [sessiondatecompontents Year] = = 2014;
BOOL isswiftsession = Namecontainsswift && iscurrentyear;


if (isswiftsession) {
Do something very cool
}


ternary operator





Ternary operators are guaranteed to be readable.


code as follows:

Recommended
result = a > B? x:y;


Not recommended
result = a > B? x = c > d? C:d: y;


The following expression is more dexterous when the second argument (if branch) of the ternary operator returns the same object as the object already examined in the conditional statement:
code as follows:

Recommended
Result = object? : [Self CreateObject];


Not recommended
Result = object? object: [Self CreateObject];


Error Handling





Some methods pass arguments that return an error reference, and you should check the return value of the method instead of the error reference when using such a method.


 code as follows:

Recommended
Nserror *error = nil;
if (![ Self Trysomethingwitherror:&error]) {
Handle Error
}

Case in a switch statement, if only one line of code can be added without braces, but multiple lines need to be added.
code as follows:

Switch (condition) {
Case 1:
// ...
Break
Case 2: {
// ...
Multi-line example using braces
Break
}
Case 3:
// ...
Break
Default
// ...
Break
}

Enum Type





Use the Ns_enum () macro to define enumerations, which have more powerful type checking and code completion.


 code as follows:

typedef ns_enum (Nsuinteger, zocmachinestate) {
Zocmachinestatenone,
Zocmachinestateidle,
Zocmachinestaterunning,
Zocmachinestatepaused
};





Variable
use long, descriptive methods and variable names as much as possible.


 code as follows:

Recommended
UIButton *settingsbutton;


Not recommended
UIButton *setbut;


Constants should be named by the Hump method and prefixed by the relevant class name.
 code as follows:

Recommended
static const Nstimeinterval zocsigninviewcontrollerfadeoutanimationduration = 0.4;


Not recommended
static const Nstimeinterval Fadeouttime = 0.4;


It is recommended that constants be used instead of string literals and numbers. It can be easily reused and quickly modified.





Constants should be declared static constants with static, rather than #define, unless they are explicitly used as macros.


 code as follows:

Recommended
Static NSString * Const Zoccachecontrollerdidclearcachenotification = @ "Zoccachecontrollerdidclearcachenotification" ;


static const CGFloat zocimagethumbnailheight = 50.0f;

Not recommended
#define COMPANYNAME @ "Apple Inc."
#define MagicNumber 42


Constants if they need to be exposed to the outside, in the header file in this form:
 code as follows:

extern nsstring *const zoccachecontrollerdidclearcachenotification;

and assigns the value to it in the implementation file.





Only public constants are required to add namespaces as prefixes. Although the naming of private constants in the implementation file can follow a different pattern, you can still follow this rule.



A space should be added between the method name and the method type (-/+ symbol).



A space interval should also be used between the method segments.



There should be a descriptive keyword before the argument.



As little as possible with the word "and", it should not be used to clarify multiple parameters.


 code as follows:

Recommended
-(void) Setexampletext: (NSString *) Text Image: (UIImage *) image;
-(void) SendAction: (SEL) Aselector to: (ID) anobject forallcells: (BOOL) flag;
-(ID) Viewwithtag: (nsinteger) tag;
-(Instancetype) Initwithwidth: (cgfloat) Width height: (cgfloat) height;


Not recommended
-(void) Sett: (NSString *) text I: (uiimage *) image;
-(void) SendAction: (SEL) Aselector:(ID) anobject:(BOOL) flag;
-(ID) Taggedview: (nsinteger) tag;
-(Instancetype) Initwithwidth: (cgfloat) Width andheight: (cgfloat) height;
-(Instancetype) Initwith: (int) width and: (int) height; Never do this.


Use literal values to create immutable Nsstring,nsdictionary,nsarray and NSNumber objects.





In this way, be careful not to put nil in Nsarray and nsdictionary, which can cause crashes.


 code as follows:

Nsarray *names = @[@ "Brian", @ "Matt", @ "Chris", @ "Alex", @ "Steve", @ "Paul"];
Nsdictionary *productmanagers = @{@ "IPhone": @ "Kate" @ "IPad": @ "Kamal", @ "Mobile Web": @ "Bill"};
NSNumber *shoulduseliterals = @YES;
NSNumber *buildingzipcode = @10018;

Don't do this:
 code as follows:

Nsarray *names = [Nsarray arraywithobjects:@ "Brian", @ "Matt", @ "Chris", @ "Alex", @ "Steve", @ "Paul", nil];
Nsdictionary *productmanagers = [nsdictionary Dictionarywithobjectsandkeys: @ "Kate", @ "IPhone", @ "Kamal", @ "IPad", @ " Bill ", @" Mobile Web ", nil];
NSNumber *shoulduseliterals = [NSNumber numberwithbool:yes];
NSNumber *buildingzipcode = [NSNumber numberwithinteger:10018];

Avoid creating variable arrays in this way:
 code as follows:

Nsmutablearray *amutablearray = [@[] mutablecopy];

In this way, there are problems in terms of efficiency and readability.





Efficiency: An unnecessarily variable group is discarded immediately after it is created and is not necessary.



Readability: The readability is not good.


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.