IOS coding specification for iOS development (36)

Source: Internet
Author: User

1. format the code ctrl + I


The position of the asterisk (*) In the cursor pointer
▪For example, NSString * varName;


Trim space VS tabs
▪Only spaces are allowed, and the editor is set to 1 TAB = 4 characters indented.


The length of each line
▪Each line cannot exceed 100 characters
▪With a 15-inch Macbook Pro, each line can contain 100 characters to maximize simultaneous editor and iPhone Simulator
▪Google's 80-character standard is a little small, which leads to too frequent line breaks (Objectve-C code is generally very long)
▪Use "Xcode => Preferences => TextEditing => check Show Page Guide/Input
100 => OK "to set the reminder


{} Each braces occupies a single row,
Description and definition of the merge Method
▪Leave a space between-+ and the return value, and leave no space between the method name and the first parameter. For example:
-(Void) doSomethingWithString :( NSString *) theString
{
...
}
▪When the parameter is too long, each parameter occupies one line and is aligned with a colon. For example:
-(Void) doSomethingWith :( GTMFoo *) theFoo
Rect :( NSRect) theRect
Interval :( float) theInterval
{
...
}
▪If the method name is shorter than the parameter name, each parameter occupies a line and is Indented by at least four characters and vertically aligned (rather than using colons)
Alignment ). For example:
-(Void) short :( GTMFoo *) theFoo
LongKeyword :( NSRect) theRect
EvenLongerKeyword :( float) theInterval
{
...
}


Invoke Method
▪Calling Methods follows the habit of declaring methods. Exception: If the given source file has followed a certain habit, continue to follow that habit.
▪All parameters should be in the same line, or each parameter occupies one line and is aligned with a colon. For example:
[MyObject doFooWith: arg1 name: arg2 error: arg3];
Or
[MyObject doFooWith: arg1
Name: arg2
Error: arg3];
▪Like method declaration, if colon alignment cannot be used, each parameter has one line, four characters in indentation, and vertical (rather
Use colons ). For example:
[MyObj short: arg1
LongKeyword: arg2
EvenLongerKeyword: arg3];


Users @ public and @ private
▪@ Public and @ private use a separate line without indentation


◦ Protocals
▪No spaces are left between the type identifier, proxy name, and angle brackets.
▪This rule also applies to: class declaration, instance variable, and method declaration. For example:
@ Interface MyProtocoledClass: NSObject <NSWindowDelegate> {
@ Private
Id <MyFancyDelegate> _ delegate;
}
-(Void) setDelegate :( id <MyFancyDelegate>) aDelegate;
@ End
▪If the class declaration contains multiple protocal, each protocal occupies one line and is Indented by two characters. For example:
@ Interface CustomViewController: ViewController <
AbcDelegate,
DefDelegate
> {
...
}


Ii. Name


CATEGORY Class Name
▪The first letter of the Class name (and its category name and protocal name) is capitalized.
▪In code for specific applications, class names should avoid prefix. Each class uses the same prefix to affect readability.
▪Prefix is recommended in multi-application-oriented code. Example: GTMSendMessage


Category Name
▪To be improved


Pipeline method name
▪The method name starts with lowercase letters and uses uppercase letters to separate words. The method parameters use the same rules.
▪The method name + parameter should be read as much as possible like a sentence (for example, :) (incorrect, avoid it as much as possible, programming is not an article, stick to the C ++ style ). Here, let's look at Apple's naming rules for methods.
▪The method name and variable name of getter must be the same. You cannot use the "get" prefix. For example:
-(Id) getDelegate; // disable
-(Id) delegate; // opposite
▪This rule is only applicable to Objective-C code and C ++ code.


Variable name
▪The full name of the variable name should be easy to use, and the first letter is lowercase, and the word is separated in the form of an upper letter
▪The member variables use "_" as the prefix (for example, "NSString * _ varName ;". Although this conflicts with Apple's standard (using "_" as the suffix), "_" is still used as the prefix for the following reasons.
▪Using "_" as the prefix makes it easier to differentiate "attributes (self. userInfo)" and "member variables (_ userInfo)" in the IDE with the code auto-complementing function )"
▪Constants (# define, enums, const, etc.) Use lowercase "k" as the prefix, and the first letter is capitalized to separate words. For example, kInvalidHandle


3. Notes
Pending completion


Iv. Unique rules of Cocoa and Objective-C
Use @ private as the alias member variable. For example:
@ Interface MyClass: NSObject {
@ Private
Id _ myInstanceVariable;
}
// Public accessors, setter takes ownership
-(Id) myInstanceVariable;
-(Void) setMyInstanceVariable :( id) theVar;
@ End


◦ Indentify Designated Initializer
▪To be improved


Extends Override Desingated Initializer
▪To be improved


Token Initialization
▪In the initialization method, do not initialize the variable to "0" or "nil", which is redundant.
▪All newly created objects (except isa) in the memory are 0, so you do not need to reinitialize them as "0" or "nil"


Consumer avoids explicit calling + new Method
▪Do not call NSObject's class method + new directly or reload it in the subclass. Use the alloc and init Methods


Keep public APIs simple
▪To be improved


Dependencies # import VS # include
▪Use # import to introduce Ojbective-C and Ojbective-C ++ header files, and use # include to introduce C and C ++ header files.


Parse import root framework (root frameworks), not individual files
▪Although sometimes we only need a few header files of the framework (such as Cocoa or Foundation ),
It runs faster. Because the root framework (root frameworks) is usually precompiled, loading is faster. Strong again
Call: Use # import instead of # include to introduce the Objective-C framework. For example:
# Import <Foundation/NSArray. h> // disable
# Import <Foundation/NSString. h>
...
# Import <Foundation/Foundation. h> // Origin


When creating an object, use autorelease whenever possible.
▪When creating a temporary object, try to remove autorelease in the same line at the same time, instead of using a separate release statement.
▪Although this will be a little slow, it can prevent memory leakage caused by early return or other unexpected situations.
It is worthwhile. For example:
// Avoid this (unless you have performance considerations)
MyController * controller = [[MyController alloc] init];
//... The code here may return...
[Controller release];


// This is better
MyController * controller = [[MyController alloc] init] autorelease];


◦ Autorelease first, then retain
▪When assigning values to an object, follow "autorelease first, then retain"
▪When assigning a new object to a variable, you must first release the old object; otherwise, memory leakage occurs. Very popular on the market
In the case of handle using multiple methods, select "autorelease first, then retain ".
Error. Note: In the loop, this method will "fill" the autorelease pool, slightly affecting the efficiency,
Google and I (: P) think this price is acceptable. For example:
-(Void) setFoo :( GMFoo *) aFoo {
[Foo _ autorelease]; // If foo _ and aFoo are the same object (foo _ = aFoo), dealloc will not be called
Foo _ = [aFoo retain];
}


The sequence of includealloc must be the same as that of variable declaration.
▪This facilitates review code
▪If other methods are called to release variables in dealloc, the release variables will be clearly marked as annotations.


Setter of the ◦ NSString attribute uses "copy"
▪Do not use retain to prevent accidental modification of NSString values. For example:
-(Void) setFoo :( NSString *) aFoo {
[Foo _ autorelease];
Foo _ = [aFoo copy];
}
Or
@ Property (nonatomic, copy) NSString * aString;


Throwing Exceptions)
▪To be improved


Inspect nil
▪Check nil only when there is business logic requirement, not to prevent crash
▪Sending messages to nil does not cause system crash, and Objective-C is responsible for processing during runtime.


◦ BOOL trap
▪Be careful when converting int values to BOOL. Avoid direct comparison with YES
▪In Objective-C, BOOL is defined as unsigned char, which means it is not only YES (1) and NO (0)
It can also be another value. Direct int conversion (cast or convert) to BOOL is prohibited.
▪Common Errors include converting the result of the array size, pointer value, or bitwise operator (cast or convert)
BOOL, because the result of this BOOL value depends on the last digit of the integer value.
▪To convert an integer value to BOOL, use the ternary operator to return YES/NO, or use the bitwise operator (&, | ,!)
▪The conversion between BOOL, _ Bool, and bool is safe, but the conversion between BOOL and Boolean is not safe, so
Think of Boolean as an integer.
▪In Objective-C, only BOOL is allowed
▪For example:
// Disable
-(BOOL) isBold {
Return [self fontTraits] & NSFontBoldTrait;
}
-(BOOL) isValid {
Return [self stringValue];
}
// Opposite
-(BOOL) isBold {
Return ([self fontTraits] & NSFontBoldTrait )? YES: NO;
}
-(BOOL) isValid {
Return [self stringValue]! = Nil;
}
-(BOOL) isEnabled {
Return [self isValid] & [self isBold];
}
▪You cannot directly compare BOOL with YES/NO, for example:
// Disable
BOOL great = [foo isGreat];
If (great = YES)
...
// Opposite
BOOL great = [foo isGreat];
If (great)
...


Region attributes
▪Name: it is the same as the member variable whose prefix "_" is removed. Use @ synthesize to associate the two variables. For example:
// Abcd. h
@ Interface MyClass: NSObject {
@ Private
NSString * _ name;
}
@ Property (copy, nonatomic) NSString * name;
@ End


// Abcd. m
@ Implementation MyClass
@ Synthesize name = _ name;
@ End
▪Position: the attribute declaration is followed by the member variable block, with a blank line in the middle without indentation. As shown in the preceding example:
▪Strict permission: Use readonly for attributes that do not require external modification.
▪NSString uses copy instead of retain
▪@ Dynamic is used for CFType. @ synthesize is not allowed.
▪Use nonatomic unless required


5. Cocoa Pattern


Delegate Pattern (Delegate)
▪The delegate object uses assign, and retain is not allowed. Because retain will cause the cyclic index to cause memory leakage,
In addition, this type of Memory leakage cannot be detected by Instrument, making debugging extremely difficult.
▪The member variable is named _ delegate and the attribute name is delegate.


Using Model/View/Controller
▪Separation of Model and View
▪Not much explanation
▪The Controller is independent of View and Controller.
▪Do not add too many business logic code to the view-related classes, which makes the code reusable very poorly.
▪The Controller is responsible for the business logic code, and the Controller code is irrelevant to the view as much as possible.
▪Use @ protocal to define callback APIs. If not all methods are required, use @ optional to mark


Vi. Others
The initialize init method and dealloc method are the most common methods, so they are placed at the beginning of the class implementation.
Use spaces to align the same variables and attributes, and use empty rows to group

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.