iOS naming conventions (reprint)

Source: Internet
Author: User

Reprint Address: http://www.cnblogs.com/qiqibo/archive/2012/09/05/2671553.html

Body:
• Formatting code
? The position of the pointer "*" number
? such as: NSString *varname;
? Space VS Tabs
? Allow only spaces to set the editor to 1 tab = 2 Character indent
? The length of each line
? No more than 100 characters per line
? With 15-inch MacBook Pro size, 100 characters per line maximizes the ability to simultaneously allow the editor and iphone simulator
? Google's 80-character standard is a bit small, which leads to too-frequent line breaks (OBJECTVE-C code is generally very long)
? Check Show page guide/input by "Xcode = Preferences = Textediting ="
"OK" to set reminders
? Declaration and definition of a method
? Leave 1 spaces between the-or + and the return values, without a space between the method name and the first argument. Such as:
-(void) dosomethingwithstring: (NSString *) thestring {
...
}
? When the parameter is too long, each parameter takes one row, aligned with a colon. Such as:
-(void) Dosomethingwith: (Gtmfoo *) Thefoo
Rect: (nsrect) Therect
Interval: (float) Theinterval {
...
}
? If the method name is shorter than the parameter name, each parameter occupies a row, indents at least 4 characters, and is vertically aligned instead of using a colon
Alignment). Such as:
-(void) Short: (Gtmfoo *) Thefoo
Longkeyword: (nsrect) Therect
Evenlongerkeyword: (float) Theinterval {
...
}
? Invocation of the method
? The calling method inherits the habit of declaring methods. Exception: If a given source file has complied with a habit, continue to follow that habit.
? All parameters should be in the same row, or each parameter takes one row and is aligned with a colon. Such as:
[MyObject dofoowith:arg1 name:arg2 ERROR:ARG3];
Or
[MyObject Dofoowith:arg1
Name:arg2
ERROR:ARG3];
? As with the declaration of a method, if you cannot use a colon alignment, each parameter is one line, 4 characters in indentation, and perpendicular to it (not
aligned with a colon). Such as:
[MYOBJ Short:arg1
Longkeyword:arg2
EVENLONGERKEYWORD:ARG3];
? @public and @private
? @public and @private use a separate line, and indent 1 characters
? Protocals
? Type identifier, proxy name, and no spaces between angle brackets.
? The same rule applies to: class declarations, instance variables, and method declarations. Such as:
@interface myprotocoledclass:nsobject<nswindowdelegate> {
@private
Id<myfancydelegate> _delegate;
}
-(void) Setdelegate: (id<myfancydelegate>) adelegate;
@end
? If the class declaration contains more than one protocal, each protocal occupies a row and is indented by 2 characters. Such as:
@interface customviewcontroller:viewcontroller<
Abcdelegate,
Defdelegate
> {
...
}
• naming
? Class name
? The first letter of the class name (and its category name and protocal name), written using the first letter capitalized form
Split words
? In code that targets specific applications, the class name should try to avoid using prefixes, and each class uses the same prefix to affect readability.
? Prefixes are recommended in code that is intended for multi-app use. such as: Gtmsendmessage
? Category Name
? Ready to be perfected
? Method name
? The first letter of the method name is lowercase, and the word is split with the first letter capitalized. The parameters of the method use the same rules.
? The method name + parameter should read as much as possible like a sentence (for example:). Here's a look at Apple's specification of method naming.
? The getter's method name and variable name should be the same. The "get" prefix is not allowed. Such as:
-(ID) getdelegate; Ban
-(ID) delegate; Enemies
? This rule is for OBJECTIVE-C code only, C + + code uses C + + habits
? Variable name
? Variable names should be used with an easy-to-use full name, with the first letter lowercase and the first letter capitalized to divide the word
? The member variable is prefixed with "_" (For example: "NSString *_varname;". While this is in keeping with Apple's standards (making
Conflicts with "_" as a suffix, but "_" is still used as the prefix for the following reasons.
? Using "_" as a prefix makes it easier to differentiate between "properties" in the IDE with code auto-completion functionality
(Self.userinfo) "and" member variable (_userinfo) "
? Constants (#define, enums, const, and so on) use lowercase "k" as the prefix and capitalize the first letter to divide the word. Such as:
Kinvalidhandle
• Notes
? Ready to be perfected
Rules peculiar to cocoa and objective-c
? Member variables use @private. Such as:
@interface Myclass:nsobject {
@private
ID _myinstancevariable;
}
Public accessors, setter takes ownership
-(ID) myinstancevariable;
-(void) setmyinstancevariable: (ID) Thevar;
@end
? Indentify designated Initializer
? Ready to be perfected
? Override desingated Initializer
? Ready to be perfected
? Initialization
? In the initialization method, do not initialize the variable to "0" or "nil", which is superfluous
? All newly created objects in memory (except for ISA) are 0, so there is no need to repeat the initialization to "0" or "nil"
? Avoid explicitly calling the +new method
? It is forbidden to call NSObject's class method +new directly, and not to overload it in subclasses. Using the Alloc and Init methods
? Maintaining the simplicity of the public API
? Ready to be perfected
? #import VS #include
? Introduction of Ojbective-c and ojbective-c++ header files using #import, introduction of C and C + + headers using #include
File
? 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), but the introduction of the root file compilation
The device will run faster. Because the root frameworks is typically precompiled, loading is faster. Again strong
Tune: Use #import instead of #include to introduce the OBJECTIVE-C framework. Such as:
#import <Foundation/NSArray.h>//prohibited
#import <Foundation/NSString.h>
...
#import <Foundation/Foundation.h>//rival
? Try to use Autorelease when creating objects
? When creating a temporary object, try to autorelease the same line at the same time, rather than using a separate release statement
? While this can be a bit slower, this prevents memory leaks due to early return or other unexpected conditions.
It is worthwhile to look at it overall. Such as:
Avoid this use (unless there is a performance consideration)
mycontroller* controller = [[Mycontroller alloc] init];
// ... The code here may return in advance ...
[Controller release];
It's better.
mycontroller* controller = [[[Mycontroller alloc] init] autorelease];
? First Autorelease, then retain.
? When assigning a value to an object, follow the "autorelease first, then retain"
? When assigning a newly created object to a variable, release the old object first, or the memory leaks. The market has a very
Many methods to handle this situation, the choice of "first autorelease, then retain" method, this method is not easy to draw
into error. Note: This method "fills" The Autorelease pool in a loop, slightly affecting efficiency, but
Google and I (:P) think the price is acceptable. Such as:
-(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 order of Dealloc is the same as the order of the variable declarations
? This facilitates review code
? If other methods are called in the Dealloc to release the variable, the release variable is annotated in the form of a note
? The setter of the NSString property uses "copy"
? It is forbidden to use retain to prevent accidental modification of the value of the NSString variable. Such as:
-(void) Setfoo: (NSString *) Afoo {
[Foo_ Autorelease];
Foo_ = [Afoo copy];
}
Or
@property (nonatomic, copy) NSString *astring;
? Avoid throwing exceptions (throwing Exceptions)
? Ready to be perfected
? A check on nil
? Check nil only when there is a business logic requirement, not to prevent crashes
? Sending messages to nil does not cause the system to crash, and the OBJECTIVE-C runtime is responsible for processing.
? BOOL Traps
? Special care should be taken when converting int values to bool. Avoid direct and yes comparisons
? In Objective-c, BOOL is defined as unsigned char, which means that in addition to YES (1) and NO (0) it
It can also be a different value. It is forbidden to convert int directly (cast or convert) to bool.
? Common errors include converting the size of an array, the pointer value, or the result of a bitwise operator (CAST or convert) to
BOOL, because the result of the bool value depends on the last digit of the integer value
? method 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 secure, but the conversion between bool and Boolean is not secure, so
The boolean is considered an integer value.
? In Objective-c, only bool is allowed
? Such as:
Ban
-(BOOL) IsBold {
return [self fonttraits] & nsfontboldtrait;
}
-(BOOL) IsValid {
return [self stringvalue];
}
Enemies
-(BOOL) IsBold {
return ([Self fonttraits] & nsfontboldtrait)? Yes:no;
}
-(BOOL) IsValid {
return [self stringvalue]! = nil;
}
-(BOOL) isenabled {
return [self isValid] && [self isbold];
}
? It is forbidden to compare bool and yes/no directly, such as:
Ban
BOOL great = [foo isgreat];
if (great = = YES)
...
Enemies
BOOL great = [foo isgreat];
if (great)
...
? Property
? Naming: The same as the member variables that remove the "_" prefix, use @synthesize to connect the two. Such as:
Abcd.h
@interface Myclass:nsobject {
@private
NSString *_name;
}
@property (copy, nonatomic) NSString *name;
@end
Abcd.m
@implementation MyClass
@synthesize name = _name;
@end
? Location: The declaration of the property immediately follows the member variable block, with an empty line in the middle, without indentation. As shown in the example above
? Strict permissions: Use ReadOnly for attributes that do not require external modification
? NSString using copy rather than retain
? Cftype use @dynamic, prohibit use of @synthesize
? Unless necessary, use nonatomic
Cocoa Pattern
? Delegate Pattern (delegate)
? The delegate object uses assign, which prohibits the use of retain. Because retain causes a memory leak due to a cyclic index,
And this type of memory leak cannot be discovered by instrument and is extremely difficult to debug
? The member variable is named _delegate and the property name is delegate
? Model/view/controller
? Model and view separation
? No more explanations.
? Controller independent of view and controller
? Do not add too much business logic code to the view-related classes, which makes the code reusability very poorly
? The controller is responsible for the business logic code, and the controller's code is independent of view
? Use @protocal to define callback APIs, and if not all methods are required, use @optional to mark
• Other
? The Init and Dealloc methods are the most common methods, so put them at the beginning of the class implementation
? Use spaces to align the same variables, attributes, and line breaks to group

iOS naming conventions (reprint)

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.