Dot notation syntax Properties and idempotent methods (methods that return the same result when called multiple times) are accessed using dot notation, and all other methods use square bracket notation. Good style:
spacing A single space is required between binary operators and their arguments, and no space is required between unary operators, casts, and their arguments. A single space is required after keywords and before parentheses.
Place one space on each side of the square brackets in array and dictionary literals. NSArray *theShit = @[ @1, @2, @3 ]; Dictionary literals have no space between the key and the colon, and one space between the colon and the value. NSDictionary *keyedShit = @{ GHDidCreateStyleGuide: @YES }; In a C function declaration, no space is left before the left parenthesis, and the function name should have a namespace identifier like a class. Good style: void RNCwesomeFunction(BOOL hasSomeArgs); Long literals should be split across multiple lines. Good style:
Use 4 spaces for indentation of each line of code. Do not use tabs for indentation. The left curly brace following a method signature and other keywords (if/else/switch/while, etc.) always appears on the same line as the statement, while the right curly brace occupies a separate line. Good style:
If there are multiple functional areas within a method, blank lines can be used to separate the functional areas. Each line of code should not exceed 100 characters. Each method is preceded by a 99-character wide comment line. Comment lines can improve the code's recognizability compared to blank lines. When a line of code is very long, comment lines also serve as out-of-bounds detection. Comment lines: ////////////////////////////////////////////////////////////////////////////////////////////////////////// Conditional Statements All logic blocks must be surrounded by curly braces, even if the conditional body only needs one line of code. Good style practices:
Bad style: if (!error) return success; or: if (!error) return success; Ternary Operator Long ternary operators should be enclosed in parentheses. The ternary operator is only used for assignment and parameterization.
The coalesced nil ternary operator should be avoided if possible. Bad style:
Multiple branching conditions should use if statements or be refactored into instance variables. Good style:
Bad style:
Exception and Error Handling Do not use exceptions (NSException) in flow control statements. Exceptions are only used to indicate programmer errors. To indicate an error, use NSError*. When a method returns an error parameter by reference, the status of the return value should be checked, not the status of the error parameter. Good style:
Bad style:
Assigning a non-Null value to an error parameter when the method is executed successfully will cause the path to jump to the false conditional branch (and then the program crashes). acting Except for inheriting a class or implementing a protocol, only use the class declaration @class directive in the header file, and do not use #import to import the class header file. If a delegate has only a few methods, such as submit and cancel, it is recommended to use blocks to write action response codes. Since the declaration of proxy methods is generally very long, the proxy object and other protocol objects must be placed below the instance variable definition, otherwise the alignment of the instance variable definition will be disrupted. When multiple protocols need to be implemented, separate each protocol name into a separate line. Good style:
method A method name first describes what is returned, followed by the circumstances under which it is returned. The type of the arguments passed in is described before the colon in the method signature. The following format syntax is used for class and instance method names:
Cocoa naming example:
Good naming style for custom methods:
When you need to get another type of object value, the method naming format syntax is as follows:
Good naming style for custom methods:
Method signatures should be as clear as possible. Bad style:
Good style:
A space should be placed after the method type modifier +/-, and a space should be placed between each parameter name. Good style:
If the method name is particularly long, split the method name into multiple lines. Good style:
Do not declare private instance variables and methods in header files. Instead, declare private variables and methods in the class extension of the implementation file. Bad style:
Constructors should usually return instance types rather than id types. parameter Commonly used prefixes before method parameter names include "the", "an", and "new". Good style:
variable Variable names should be self-descriptive. Except in for() loop statements, single-letter variables should be avoided (such as i, j, k, etc.). The naming prefixes of the current object in general loop statements include "one", "a/an". For simple single objects, use "item". Good style:
The asterisk indicator of a pointer variable should be next to the variable, such as NSString *text, not NSString* text or NSString * text. Try to use properties instead of instance variables. Except for accessing instance variables synthesized by properties in initialization methods (init, initWithCoder:, etc.), dealloc methods, and custom setter and getter methods, use properties for access in other situations. Good style:
Bad style:
When you use the @synthesize directive, the compiler automatically creates an instance variable for you starting with an underscore _, so there is no need to declare both the instance variable and the property. Bad style:
Good style:
Do not use @synthesize unless required by the compiler. Note that @optional properties in @protoco protocols must be explicitly synthesized using the @synthesize directive. Abbreviations Although method names should not use abbreviations, some abbreviations have been used repeatedly in the past, so using these abbreviations can better express the meaning of the code. The following table lists the abbreviations that Cocoa accepts. ................................................................................. Here are some commonly used acronyms: ASCII PDF XML HTML URL RTF HTTP TIFF JPG PNG GIF LZW ROM RGB CMYK MIDI FTP name Method and variable names should be as self-describing as possible. Good style:
Bad style:
For NSString, NSArray, NSNumber, or BOOL types, the name of the variable generally does not need to indicate its type. Good style:
Bad style:
If the variable is not of the above basic common types, the variable name should reflect its own type. But sometimes only one instance of a certain class is needed, so only the name based on the class name is needed.
In most cases, variables of type NSArray or NSSet only need to use the plural form of the word (such as mailboxes), without including "mutable" in the name. If the plural variable is not of type NSArray or NSSet, you need to specify its type. Good style:
Since Objective-C does not support namespaces, to prevent namespace conflicts, add a three-letter uppercase prefix (such as RNC) to class names and constant variable names. This rule can be ignored for Core Data entity names. If you subclass a standard Cocoa class, it is a good practice to merge the prefix with the parent class name. For example, a class that inherits UITableView can be named RNCTableView. Constant variable names are written in camel case (the first letter of the first word is lowercase, and the first letter of the remaining words is uppercase. For example, firstName instead of first_name or firstname.) and use the associated class name as its naming prefix. Recommended practice:
Not recommended:
Underline When using properties, instance variables should be accessed and set using self. Local variable names should not contain underscores. Instance variable names must be prefixed with an underscore _ to narrow the range of options that Xcode automatically completes. Notes Comments can be used to explain the code when necessary. When updating the code, be sure to update the comments to prevent misunderstanding of the code. Use javadoc-style documentation comment syntax. The first line of the comment is a summary of the comment API, and subsequent comment lines explain the code in more detail. Good style:
init and dealloc The 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 below the dealloc method. The structure of the init method should look like this:
Literals For NSString, NSDictionary, NSArray, and NSNumber classes, when you need to create immutable instances of these classes, you should use the literal representation of these classes. When using literal representation, nil does not need to be passed into NSArray and NSDictionary as a literal value. This syntax is compatible with older iOS versions, so it can be used in iOS5 or older versions. Good style:
Bad style:
Avoid using certain types of numbers unless necessary (use 5.3 instead of 5.3f). CGRect Function Prefer using C99 structure initialization syntax to using structure helper functions (such as CGRectMake()). CGRect rect = {.origin.x = 3.0, .origin.y = 12.0, .size.width = 15.0, .size.height = 80.0 }; When accessing the x, y, width, and height members of the CGRect structure, you should use the CGGeometry function instead of directly accessing the structure members. Apple's introduction to the CGGeometry function: 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 should 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:
Bad style:
constant Prefer constant variables rather than embedded string literals or numbers, because constant variables can easily reuse commonly used variable values (such as π), and can quickly modify values without search and replacement. Constant variables should be declared as static types, and do not use #define, unless the constant variable is used as a macro. Good style:
Bad style:
Enumeration Types When using the enum keyword, it is recommended to use the fixed base type syntax recently introduced by Apple, because this will get strong type checking and code completion. The SDK now includes a fixed base type macro - NS_ENUM(). NS_ENUM was introduced in iOS 6. To support previous iOS versions, use a simple inline method:
Good style:
Private properties Private properties should be declared in the class extension of the implementation file (that is, an anonymous category). Do not declare private properties in a named category (such as RNCPrivate or private) unless you are extending another class. Good style:
Naming pictures The names of images should be consistent, with the image's purpose as the image file name. The file name should be in camel case, and can be followed by a custom class name or custom attribute name (if there is an attribute name), and can also be followed by a description of the color and/or location, and the final state of the image. Good style: RefreshBarButtonItem / RefreshBarButtonItem@2x and RefreshBarButtonItemSelected / RefreshBarButtonItemSelected@2x ArticleNavigationBarWhite / ArticleNavigationBarWhite@2x and ArticleNavigationBarBlackSelected / ArticleNavigationBarBlackSelected@2x. Images that are used for similar purposes should be managed separately using an image folder. Boolean Type Because nil is interpreted as NO, there is no need to compare it with nil. Do not compare variables with YES directly, because YES is defined as 1 and BOOL type is an 8-bit unsigned int, that is, the value of BOOL is not only 1 or 0. Good style:
Bad style:
For a BOOL value: Two best practices:
Bad style:
If a BOOL property name is an adjective, omitting the "is" prefix is allowed, but the accessor must specify a conventional method name, such as: @property (assign, getter=isEditable) BOOL editable; Singleton Shared singleton instances should be created using thread-safe patterns.
appendix Xcode Themes Most developers use the default font color theme of Xcode. In fact, a good theme can not only improve the recognition of source code, but also add fun to coding. Here are two links to Xcode font color themes: https://github.com/vinhnx/Ciapre-Xcode-theme https://github.com/tursunovic/xcode-themes Code Snippet Skilled use of the code snippet library can increase your coding speed. In Xcode4, open a project and make the editing area visible on the right, then click the fourth {} icon on the right bottom panel to open the code snippet library, where you can drag commonly used codes. The following is a link to the latest open source code snippet library: https://github.com/mattt/Xcode-Snippets |
<<: 8 pictures to understand Java
>>: Why is the entry-level capacity of iPhone only 16GB?
Eggs are a common sight on the tables of every ho...
First release resource introduction 1. Home page ...
When it comes to online event planning, the most ...
Compared with previous years, this year's Dou...
The May Day holiday is just a few days away, and a...
Bello! Banana! The cute and naughty Minions are b...
As of January this year, Xiaohongshu has more tha...
The shelf life of bottled water is not the shelf ...
Recently, Chinese scientists discovered an unknow...
The final effect of an advertisement is often det...
Osteoporosis is an invisible killer that can slow...
With the development of the times, users' imm...
Students who have been to Gansu, can you guess wh...
How much do you know about "Shenzhou" a...
The TV series "Story of Yanxi Palace" i...