IOS code writing style Specification

Source: Internet
Author: User

IOS code writing style Specification
Point mark syntaxAttribute and power methods (multiple calls are the same as the results returned by one call) use the dot mark syntax for access. Otherwise, use the square brackets mark syntax.Good style: View. backgroundColor = [UIColor orangeColor]; [UIApplication sharedApplication]. delegate;Bad style: [View setBackgroundColor: [UIColor orangeColor]; UIApplication. sharedApplication. delegate;SpacingA space must be placed between a binary operator and a parameter. A space is not placed between the unary operator, forced type conversion, and parameters. Place a space before parentheses after the keyword.

Void * ptr = & value + 10*3;

NewType a = (NewType) B;

 

For (int I = 0; I <10; I ++ ){

DoCoolThings ();

}

 

There is a space on each side of square brackets of the array and dictionary types.

NSArray * theShit = @ [@ 1, @ 2, @ 3];

There is no space between the dictionary literal value Key and the colon, and there is a space between the colon and the value. NSDictionary * keyedShit ={ GHDidCreateStyleGuide: @ YES}; in the C function declaration, spaces are not reserved before the left brackets, and the function name should have a namespace Id like a class. Good style: void RNCwesomeFunction (BOOL hasSomeArgs); long nominal values should be split into multiple rows. Good style:

NSArray * theShit = @[

@ "Got some long string objects in here .",

[AndSomeModelObjects too],

@ "Moar strings ."

];

 

NSDictionary * keyedShit = @{

@ "This. key": @ "corresponds to this value ",

@ "OtherKey": @ "remoteData. payload ",

@ "Some": @ "more ",

@ "JSON": @ "keys ",

@ "And": @ "stuff ",

};

Each line of code is indented with four spaces. Do not use tab indentation. It is set to indent in Xcode Preferences. The left curly braces followed by the method signature and other keywords (if/else/switch/while) always appear in the same line as the statement, and the right curly braces exclusively occupy one row. Good style:

If (user. isHappy ){

// Do something

}

Else {

// Do something else

}

If a method has multiple functional areas, you can use blank lines to separate functional areas. Each line of code must not contain more than 100 characters. Each method previously had a 99-character comment line. The comment line can improve code recognition compared to the empty line. When a line of code is long, the comment row also plays a role in cross-border detection. Comment row: //////////////////////////////////////// //////////////////////////////////////// /////////////////// Condition StatementAll logical blocks must be enclosed by curly brackets, even if the condition body only needs to write a line of code. Good style practices:

If (! Error ){

Return success;

}

Bad style:

If (! Error)

Return success;

Or: if (! Error) return success; Ternary OperatorsLong ternary operators should be enclosed in parentheses. The ternary operator is only used for values and parameters. Blah * a = (stuff = thing? Foo: bar); Avoid merging nil ternary operators. Bad style:Blah * B = thingThatCouldBeNil? : DefaultValue; multi-branch conditions should use the if statement or be restructured into instance variables. Good style:Result = a> B? X: y; Bad style:Result = a> B? X = c> d? C: d: y; Exception and error handlingDo not use NSException in a flow control statement ). Exceptions are only used to indicate programmer errors. To indicate an error, Use NSError *. When a method returns an error parameter through reference, the status of the returned value should be checked, rather than the status of the error parameter. Good style:

NSError * error;

If (! [Self trySomethingWithError: & error]) {

// Handle Error

}

Bad style:

NSError * error;

[Self trySomethingWithError: & error];

If (error ){

// Handle Error

}

If a non-Null value is assigned to the error parameter when the method execution is successful, the path will jump to the false condition Branch (then the program will crash ). ProxyIn addition to inheriting a class or implementing a protocol, otherwise, only the class declaration @ class instruction is used in the header file, and the # import class header file is not required. If a delegate has only a few methods, such as submitting and canceling, we recommend that you use block to write the action response code. Because the declaration of the proxy method is usually very long, you must put the proxy object and other protocol objects under the instance variable definition, otherwise the alignment of the instance variable definition will be disrupted. When multiple protocols need to be implemented, each protocol name is split into individual lines. Good style:

@ Interface CustomModelViewController: TTViewController <

TTModelDelegate,

TTURLRequestDelegate

> {

MethodThe name of a method first describes what is returned, and then under what circumstances is returned. The type of the input parameter described before the colon in the method signature. The format syntax for naming the following methods and instance methods:

[Object/class thing + condition];

[Object/class thing + input: input];

[Object/class thing + identifer: input];

Cocoa naming example:

RealPath = [path stringByExpandingTildeInPath];

FullString = [string stringByAppendingString: @ "Extra Text"];

Object = [array objectAtIndex: 3];

// Class Method

NewString = [NSString stringWithFormat: @ "% f", 1.5];

NewArray = [NSArray arrayWithObject: newString];

Good naming style for custom methods:

Recipients = [email recipientsSortedByLastName];

NewEmail = [CDCEmail emailWithSubjectLine: @ "Extra Text"];

Emails = [mailbox messagesReceivedAfterDate: yesterdayDate];

When you need to obtain another type of object value, the method naming syntax is as follows:

[Object adjective + thing];

[Object adjective + thing + condition];

[Object adjective + thing + input: input];

Good naming style for custom methods:

Capitalized = [name capitalizedString];

Rate = [number floatValue];

NewString = [string decomposedStringWithCanonicalMapping];

Subarray = [array subarrayWithRange: segment];

The method signature should be clear as much as possible. Bad style:

-SortInfo // whether to return the sorting result or sort info

-RefreshTimer // returns a timer for Refresh or a refresh timer.

-Update // What to update and how to update

Good style:

-CurrentSortInfo // "current" clearly modifies the term SortInfo

-RefreshDefaultTimer // refresh is a verb.

-UpdateMenuItemTitle // an ongoing action

Place a space after the method type Modifier +/-, and a space between parameter names. Good style:-(Void) setExampleText :( NSString *) text image :( UIImage *) image; if the method name is particularly long, split the method name into multiple rows. Good style:

Color = [NSColor colorWithCalibratedHue: 0.10

Saturation: 0.82

Brightness: 0.89

Alpha: 1.00];

Do not declare private instance variables and methods in the header file. Private variables and methods should be declared in the class extension of the implementation file.
Bad style:

// MyViewController. h file

@ Interface MyViewController: UIViewController <

UITalbeViewDataSource,

UITableViewDelegate> {

@ Private:

UITableView * _ myTableView; // Private instance variable

}

// Attributes used internally

@ Property (nonatomic, strong) NSNumber * variableUsedInternally;

-(Void) sortName; // used internally only

@ End

Good style:

// Use class extension for the MyViewController. m file

@ Interface MyViewController () <

UITalbeViewDataSource,

UITableViewDelegate> {

UITableView * _ myTableView;

// The instance variable to be accessed outside is declared as an attribute, and the instance variable does not need to be declared as an external access.

NSNumber * variableUsedInternally;

}

// From Xcode4.3, You Can Do not write the method's pre-declaration. The Interface Builder and Storyboard can still find the method definition.

@ End

The constructor should usually return the instance type instead of the id type. ParametersThe prefix before the method parameter name generally includes "the", "an", and "new ". Good style:

-(Void) setTitle: (NSString *) aTitle;

-(Void) setName: (NSString *) newName;

-(Id) keyForOption: (CDCOption *) anOption

-(NSArray *) emailsForMailbox: (Fig *) theMailbox;

-(CDCEmail *) emailForRecipients: (NSArray *) theRecipients;

VariableVariable commands should be self-described as much as possible. Except for () loop statements, single-letter variables (such as I, j, k) should be avoided ). Generally, the name prefix of the current object in the loop statement includes "one" and "a/". Use "item" to name a single object. Good style:

For (I = 0; I <count; I ++ ){

OneObject = [allObjects objectAtIndex: I];

NSLog (@ "oneObject: % @", oneObject );

}

 

NSEnumerator * e = [allObjects objectEnumerator];

Id item;

While (item = [e nextObject])

NSLog (@ "item: % @", item );

The asterisk indicator of the pointer variable should be close to the variable, such as NSString * text, rather than NSString * text or NSString * text. Try to use attributes instead of instance variables. In addition to the initialization method (init, initWithCoder:, etc.), the dealloc method, and the custom setter and getter methods to access the instance variables merged by attributes, other conditions use the attributes for access. Good style:

@ Interface RNCSection: NSObject

@ Property (nonatomic) NSString * headline;

@ End

Bad style:

@ Interface RNCSection: NSObject {

NSString * headline;

}

When you use the @ synthesize command, the compiler automatically creates an instance variable starting with underscore _ for you, so you do not need to declare the instance variables and attributes at the same time. Bad style:

@ Interface RNCSection: NSObject {

NSString * headline;

}

@ Property (nonatomic) NSString * headline;

@ End

Good style:

@ Interface RNCSection: NSObject

@ Property (nonatomic) NSString * headline;

@ End

Do not use @ synthesize unless required by the compiler. Note that the @ optional attribute in the @ protoco protocol must be explicitly synthesized using the @ synthesize command. AcronymsAlthough acronyms should not be used for method naming, Some acronyms have been used repeatedly in the past, so they can better express the meaning of code. The following table lists the accepted acronyms of Cocoa. ........................................ ................ The following are some common acronyms: ascii pdf xml html url: RTF HTTP TIFF JPG PNG GIF LZW ROM RGB CMYK MIDI FTP NameMethods and variable commands should be self-described as much as possible. Good style:UIButton * settingsButton; Bad style:UIButton * setBut; For NSString, NSArray, NSNumber, or BOOL types, the variable name generally does not need to indicate its type. Good style:

NSString * accountName;

NSMutableArray * mailboxes;

NSArray * defaultHeaders;

BOOL userInputWasUpdated;

Bad style:

NSString * accountNameString;

NSMutableArray * mailboxArray;

NSArray * defaultHeadersArray;

BOOL userInputWasUpdatedBOOL;

If the variable is not a common type, the variable name should reflect its own type. However, if you only need one instance of some classes, you only need to name the instance based on the class name.

NSImage * previewPaneImage;

NSProgressIndicator * uploadIndicator;

NSFontManager * fontManager; // class name-based

In most cases, NSArray or NSSet variables only need to be in the form of multiple words (such as mailboxes), and do not need to include "mutable" in the name ". If the plural variable is not of the NSArray or NSSet type, you must specify its type. Good style:

NSDictionary * keyedAccountNames;

NSDictionary * messageDictionary;

NSIndexSet * selectedMailboxesIndexSet;

Objective-C does not support namespaces. To prevent namespace conflicts, add a prefix (such as RNC) consisting of three uppercase letters before the class name and the variable name of the common type. This rule can be ignored for the Core Data entity name. If You subclass the standard Cocoa class, it is a good practice to merge the prefix and parent class name. For example, the class that inherits UITableView can be named RNCTableView. The Writing Style of common variable names is case-sensitive (the first letter of the first word is lowercase, and the first letter of other words is capitalized. For example, firstName instead of first_name or firstname .), And use the associated class name as its naming prefix, Recommended Practices:Static const NSTimeInterval RNCArticleViewControllerNavigationFadeAnimationDuration = 0.3; Not recommended practices:Static const nstimeinteger Val fadetime = 1.7; UnderlineWhen using attributes, the instance variables should use self. for access and setting values. The local variable command must not contain underscores. The instance variable name must be prefixed with underscore _, which can narrow the range of options automatically completed by Xcode. NoteAnnotations can be used to explain the code as needed. When updating code, you must update comments to avoid misunderstanding of the Code. Use the javadoc-style document comment syntax. The first line of the annotation is a summary of the annotation API, and the subsequent annotation line is an explanation of more details of the Code. Good style:

/**

* The maximum size of a download that is allowed.

*

* If a response reports a content length greater than the max * will be canceled. This is helpful for preventing excessive memory usage.

* Setting this to zero will allow all downloads regardless of size.

*

* @ Default 150000 bytes

*/

@ Property (nonatomic) NSUInteger maxContentLength;

Init and deallocThe dealloc method should be placed at the top of the implementation method, directly after the @ synthesize or @ dynamic statement. The init method should be placed under the dealloc method. The structure of the init method should look like this:

-(Instancetype) init {

Self = [super init]; // or call the designated initalizer

If (self ){

// Custom initialization

}

 

Return self;

}

Nominal valueFor NSString, NSDictionary, NSArray, and NSNumber classes, the literal value representation of these classes should be used to create immutable instances of these classes. Nil does not need to input NSArray or NSDictionary as the literal value when the literal value is used. This syntax is compatible with the old iOS version, so it can be used in iOS5 or older versions. Good style:

NSArray * names = @ [@ "Brian", @ "Matt", @ "Chris", @ "Alex", @ "Steve", @ "Paul"];

NSDictionary * productManagers =@ {@ "iPhone": @ "Kate", @ "iPad": @ "Kamal", @ "Mobile Web": @ "Bill "};

NSNumber * shouldUseLiterals = @ YES;

NSNumber * buildingZIPCode = @ 10018;

Bad style:

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 using numbers of specific types if not necessary (5.3 should be used compared to 5.3f ). CGRect FunctionThe C99 struct initialization syntax is preferred for struct auxiliary functions (such as CGRectMake. CGRect rect = {. origin. x = 3.0 ,. origin. y = 12.0 ,. size. width = 15.0 ,. size. height = 80.0}; when you access the x, y, width, and height members of the CGRect struct, you should use the CGGeometry function without directly accessing the struct members. Apple's introduction to CGGeometry functions: All functions described in this reference that take CGRect data structures as inputs implicitly standardize those rectangles before calculating their results. for this reason, your applications shoshould avoid directly reading and writing the data stored in the CGRect data structure. instead, use the functions described here to manipulate rectangles and to retrieve their characteristics. Good style:

CGRect frame = self. view. frame;

CGFloat x = CGRectGetMinX (frame );

CGFloat y = CGRectGetMinY (frame );

CGFloat width = CGRectGetWidth (frame );

CGFloat height = CGRectGetHeight (frame );

Bad style:

CGRect frame = self. view. frame;

CGFloat x = frame. origin. x;

CGFloat y = frame. origin. y;

CGFloat width = frame. size. width;

CGFloat height = frame. size. height;

ConstantThe use of common variables is preferred, rather than embedded string literal values or numbers, because common variables can easily reuse common variable values (such as π ), at the same time, you can quickly modify the value without looking for replacement. Constant type variables should be declared as static type. Do not use # define. Except for non-type variables, they should be used as macros. Good style:

Static NSString * const RNCAboutViewControllerCompanyName = @ "The New York Times Company ";

Static const CGFloat RNCImageThumbnailHeight = 50.0;

Bad style:

# Define CompanyName @ "The New York Times Company"

# Define thumbnailHeight 2

Enumeration typeWhen using the enum keyword, it is recommended that you use the fixed basic type syntax recently introduced by Apple, because this will obtain the strong type check and Code Completion function. The SDK now contains a fixed base type macro-NS_ENUM (). NS_ENUM was introduced in iOS6. To support previous iOS versions, use the simple inline method:

# Ifndef NS_ENUM

# Define NS_ENUM (_ type, _ name) enum _ name: _ type _ name; enum _ name: _ type

# Endif

Good style:

Typedef NS_ENUM (NSInteger, RNCAdRequestState ){

RNCAdRequestStateInactive,

RNCAdRequestStateLoading

};

Private attributesPrivate attributes should be declared in the class extension of the implementation file (namely, anonymous category ). Do not declare private attributes in the named category (such as RNCPrivate or private) unless it is an extension of other classes. Good style:

@ Interface NYTAdvertisement ()

 

@ Property (nonatomic, strong) GADBannerView * googleAdView;

@ Property (nonatomic, strong) ADBannerView * iAdView;

@ Property (nonatomic, strong) UIWebView * adXWebView;

 

@ End

Image nameThe image names must be consistent, and the image object name must be described as the image object name. Naming of file names is case-sensitive. After a file name, you can follow a custom class name or custom attribute name (if there is an attribute name) you can also keep up with the color description and the final status of the/or position and image.
Good style:RefreshBarButtonItem/RefreshBarButtonItem @ 2x and others/users @ 2x ArticleNavigationBarWhite/ArticleNavigationBarWhite @ 2x and ArticleNavigationBarBlackSelected/folder @ 2x. images used for similar purposes should be managed separately using an image folder. Boolean TypeBecause nil is parsed as NO, there is NO need to compare it with nil. Do not directly compare variables with YES, because YES is defined as 1 and BOOL type is an 8-bit unsigned int, that is, the BOOL value is not only 1 or 0. Good style:

If (! SomeObject ){

}

Bad style:

If (someObject = nil ){

}

For a BOOL value: two best practices:

If (isAwesome)

If (! [SomeObject boolValue])

Bad style:

If ([someObject boolValue] = NO)

If (isAwesome = YES) // Never do this.

If a BOOL type attribute name is an adjective, ignoring the "is" prefix of the attribute name is allowed, but you need to specify the agreed method name for the accessor, for example: @ property (assign, getter = isEditable) BOOL editable; SingletonUse thread-safe mode to create a shared Singleton instance.

+ (Instancetype) sharedInstance {

Static id sharedInstance = nil;

 

Static dispatch_once_t onceToken;

Dispatch_once (& onceToken, ^ {

SharedInstance = [[self alloc] init];

});

 

Return sharedInstance;

}

AppendixMost developers of Xcode themes use Xcode default font color themes. In fact, good themes not only increase the degree of source code recognition, but also increase the fun of coding. Code snippetSkillful Use of the code snippet library can increase the encoding speed. In Xcode4, open a project and make the editing area on the right visible. Then, click the fourth {} icon in the bottom panel on the right to open the code snippet library. You can drag common code into it.

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.