### Objective-C Parameter Naming Examples Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Provides examples of common and recommended parameter naming conventions in Objective-C methods. Parameter names should be descriptive, fully spelled out, and avoid abbreviations. ```objective-c ...action:(SEL)aSelector ...alignment:(int)mode ...atIndex:(int)index ...content:(NSRect)aRect ...doubleValue:(double)aDouble ...floatValue:(float)aFloat ...font:(NSFont *)fontObj ...frame:(NSRect)frameRect ...intValue:(int)anInt ...keyEquivalent:(NSString *)charCode ...length:(int)numBytes ...point:(NSPoint)aPoint ...stringValue:(NSString *)aString ...tag:(int)anInt ...target:(id)anObject ...title:(NSString *)aString ``` -------------------------------- ### Objective-C `NSWindow` Collection Methods Example Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Provides specific examples of collection operation methods used in the `NSWindow` class. These methods demonstrate how to manage child windows, including adding, removing, and retrieving them, as well as accessing the parent window. ```objective-c - (void)addChildWindow:(NSWindow *)childWin ordered:(NSWindowOrderingMode)place; - (void)removeChildWindow:(NSWindow *)childWin; - (NSArray *)childWindows; - (NSWindow *)parentWindow; - (void)setParentWindow:(NSWindow *)window; ``` -------------------------------- ### Objective-C Method Naming: Actions Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Examples of Objective-C method naming conventions where the method performs an action on the object. Methods should start with a verb and avoid redundant keywords. ```objective-c - (void)invokeWithTarget:(id)target; - (void)selectTabViewItem:(NSTabViewItem *)tabViewItem; ``` -------------------------------- ### Objective-C Property Naming Examples (Noun and Verb) Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Provides examples of naming properties in Objective-C using nouns and verbs. Property names should be descriptive and do not require prefixes. The first letter is typically lowercase, followed by capitalized subsequent words. ```objective-c //名词属性 @property (strong) NSString *title; //动词属性 @property (assign) BOOL showsAlpha; ``` -------------------------------- ### Objective-C Function Naming Examples Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Demonstrates various Objective-C function naming patterns based on return type and parameter usage. Functions often use framework abbreviations as prefixes. ```objective-c NSHighlightRect NSDeallocateObject ``` ```objective-c unsigned int NSEventMaskFromType(NSEventType type) float NSHeight(NSRect aRect) ``` ```objective-c const char *NSGetSizeAndAlignment(const char *typePtr, unsigned int *sizep, unsigned int *alignp) ``` ```objective-c BOOL NSDecimalIsNotANumber(const NSDecimal *decimal) ``` -------------------------------- ### Objective-C Property Naming Example (Adjective with `is` Getter) Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Demonstrates how to name a property as an adjective in Objective-C, using the `getter=` attribute to specify a getter method prefixed with `is` for improved readability. ```objective-c @property (assign, getter=isEditable) BOOL editable; ``` -------------------------------- ### Objective-C File Header Comment Example Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md This snippet demonstrates the standard Objective-C file header comment format. It typically includes module, author, history, copyright, and content description. This format aids in understanding the file's purpose and its evolution. ```objective-c // // commonLib.h // TBox // Description: This file provide some covenient tool in calling library tools. One can easily include library headers he wants by declaring the corresponding macros. I hope this file is not only a header, but also a useful Linux library note. History: 2012-??-??: On about come date around middle of Year 2012, file created as "commonLib.h" 2012-08-20: Add shared memory library; add message queue. 2012-08-21: Add socket library (local) 2012-08-22: Add math library 2012-08-23: Add socket library (internet) 2012-08-24: Add daemon function 2012-10-10: Change file name as "AMCCommonLib.h" 2012-12-04: Add UDP support in AMC socket library 2013-01-07: Add basic data type such as "sint8_t" 2013-01-18: Add CFG_LIB_STR_NUM. 2013-01-22: Add CFG_LIB_TIMER. 2013-01-22: Remove CFG_LIB_DATA_TYPE because there is already AMCDataTypes.h // Created by ZC on 2017/2/18. // Copyright © 2017年 Hikvison AutoMotive Technology. All rights reserved. // ``` -------------------------------- ### Objective-C Naming Clarity Examples Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md This snippet demonstrates clear vs. unclear naming conventions in Objective-C. It emphasizes using descriptive names over abbreviations to improve code readability, especially with Xcode's auto-completion. It also shows common abbreviations that are acceptable due to widespread use. ```objective-c //清晰 insertObject:atIndex: //不清晰,insert的对象类型和at的位置属性没有说明 insert:at: //清晰 removeObjectAtIndex: //不清晰,remove的对象类型没有说明,参数的作用没有说明 remove: //清晰 settingsButton; destinationSelection setBackgroundColor: //不清晰,不要使用简写 setBut; destSel setBkgdColor: // Acceptable common abbreviations: alloc == Allocate alt == Alternate app == Application calc == Calculate dealloc == Deallocate func == Function horiz == Horizontal info == Information init == Initialize int == Integer max == Maximum min == Minimum msg == Message nib == Interface Builder archive pboard == Pasteboard rect == Rectangle Rep == Representation (used in class name such as NSBitmapImageRep). temp == Temporary vert == Vertical ``` -------------------------------- ### Objective-C Conditional Compilation Example Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Provides an example of using the `#ifdef` preprocessor directive in Objective-C for conditional compilation. This is a common use case for `#define` macros, such as enabling or disabling debug logging. ```objective-c #ifdef DEBUG // Code to be compiled only in debug builds #endif ``` -------------------------------- ### Objective-C Naming Ambiguity Examples Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md This snippet provides examples of ambiguous method or function names in Objective-C. It illustrates how names like `sendPort` or `displayName` can be interpreted in multiple ways, leading to confusion. The goal is to encourage names that clearly convey the intended action or meaning. ```objective-c //有歧义,是返回sendPort还是send一个Port? sendPort //有歧义,是返回一个名字属性的值还是display一个name的动作? displayName ``` -------------------------------- ### Objective-C Method Naming: Avoiding `get` Prefix for Properties Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Explains why the `get` prefix is generally not used for property accessors in Objective-C. The `get` prefix is typically reserved for functions that return values through multiple output parameters (function pointers). ```objective-c //三个参数都是作为函数的返回值来使用的,这样的函数名可以使用"get"前缀 - (void)getLineDash:(float *)pattern count:(int *)count phase:(float *)phase; ``` -------------------------------- ### Objective-C Method Naming: Property Access Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Illustrates Objective-C method naming for accessing object properties. The method name should directly correspond to the property name without 'get' prefixes. ```objective-c - (NSSize)cellSize; ``` -------------------------------- ### Objective-C Method and Class Commenting Styles Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md This snippet illustrates Objective-C commenting styles for methods, functions, classes, and protocols. It shows Apple's standard `/** */` style for documentation that can be easily accessed in Xcode, and `//` style for inline comments, typically placed above the code it describes. It also includes examples of using `||` for parameter and method referencing within comments. ```objective-c /** Create a new preconnector to replace the old one with given mac address. NOTICE: We DO NOT stop the old preconnector, so handle it by yourself. @param type Connect type the preconnector use. @param macAddress Preconnector's mac address. */ - (void)refreshConnectorWithConnectType:(IPCConnectType)type Mac:(NSString *)macAddress; /** Stop current preconnecting when application is going to background. */ -(void)stopRunning; /** Get the COPY of cloud device with a given mac address. @param macAddress Mac address of the device. @return Instance of IPCCloudDevice. */ -(IPCCloudDevice *)getCloudDeviceWithMac:(NSString *)macAddress; // A delegate for NSApplication to handle notifications about app // launch and shutdown. Owned by the main app controller. @interface MyAppDelegate : NSObject { ... } @end // Delegate - Sent when failed to init connection, like p2p failed. -(void)initConnectionDidFailed:(IPCConnectHandler *)handler; // Sometimes we need |count| to be less than zero. // Remember to call |StringWithoutSpaces("foo bar baz")| ``` -------------------------------- ### Objective-C Function Call Formatting Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Provides examples of correct and incorrect formatting for function calls in Objective-C. Calls can be on a single line or split across multiple lines, aligning at the ':' character. Incorrect formatting mixes single and multi-line or misaligns parameters. ```objective-c //write on one line [myObject doFooWith:arg1 name:arg2 error:arg3]; //split lines, align at ':' [myObject doFooWith:arg1 name:arg2 error:arg3]; //if first param name is short, indent subsequent ones [myObj short:arg1 longKeyword:arg2 evenLongerKeyword:arg3 error:arg4]; ``` ```objective-c //Wrong, either one line or all split [myObject doFooWith:arg1 name:arg2 error:arg3]; [myObject doFooWith:arg1 name:arg2 error:arg3]; //Wrong, align at ':' not keyword [myObject doFooWith:arg1 name:arg2 error:arg3]; ``` -------------------------------- ### Objective-C Property Attributes: Storage and Atomicity Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Explicitly list all property attributes, following the order: storage, atomicity. This improves code readability and consistency, especially for those new to the codebase. Example shows correct usage of weak, nonatomic, strong, and copy. ```objc @property (weak, nonatomic) IBOutlet UIView *containerView; @property (strong, nonatomic) NSString *tutorialName; // NSString should use 'copy' instead of 'strong' to prevent unintended modifications by subclasses like NSMutableString. @property (copy, nonatomic) NSString *tutorialName; ``` -------------------------------- ### Objective-C Delegate Method Patterns Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Provides examples of delegate method naming conventions in Objective-C. Delegate methods are triggered by specific events and are a common way to pass messages between objects. The naming typically includes the sender object's class name as the first keyword, unless there's only a `sender` parameter. ```objective-c //第一个关键词为触发委托的类名 - (BOOL)tableView:(NSTableView *)tableView shouldSelectRow:(int)row; - (BOOL)application:(NSApplication *)sender openFile:(NSString *)filename; //当只有一个"sender"参数时可以省略类名 - (BOOL)applicationOpenUntitledFile:(NSApplication *)sender; ``` -------------------------------- ### Idiomatic Boolean Checks in Objective-C Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Demonstrates the idiomatic way to check boolean values in Objective-C, using direct evaluation for objects and `BOOL` types. It advises against comparing directly with `YES`, `NO`, `true`, or `false`, and highlights that `nil` evaluates to `NO`. The example also shows how to handle boolean properties with adjective-based names using custom getters. ```objective-c // Should: if (someObject) {} if (![anotherObject boolValue]) {} // Should not: if (someObject == nil) {} if ([anotherObject boolValue] == NO) {} if (isAwesome == YES) {} if (isAwesome == true) {} // Example with getter: @property (assign, getter=isEditable) BOOL editable; // Correct boolean comparison: BOOL great = [foo isGreat]; if (great) // ...be great! // Correctly returning boolean values: - (BOOL)isBold { return ([self fontTraits] & NSFontBoldTrait) ? YES : NO; } - (BOOL)isValid { return [self stringValue] != nil; } - (BOOL)isEnabled { return [self isValid] && [self isBold]; } ``` -------------------------------- ### Declare Private Properties in Objective-C Class Extension Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Illustrates how to declare private properties in Objective-C using an anonymous class extension within the implementation file. This is the recommended approach for encapsulating properties that should not be accessible from outside the class. The example shows declaring `GADBannerView`, `ADBannerView`, and `UIWebView` as private properties. ```objective-c @interface RWTDetailViewController () @property (strong, nonatomic) GADBannerView *googleAdView; @property (strong, nonatomic) ADBannerView *iAdView; @property (strong, nonatomic) UIWebView *adXWebView; @end ``` -------------------------------- ### Objective-C Delegate Methods: Using `should`, `will`, `did` Prefixes Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Demonstrates the use of prefixes like `should`, `will`, and `did` in delegate methods to indicate the timing and purpose of the action being delegated. This helps in understanding the method's role within the delegation process. ```objective-c - (void)browserDidScroll:(NSBrowser *)sender; - (NSUndoManager *)windowWillReturnUndoManager:(NSWindow *)window; - (BOOL)windowShouldClose:(id)sender; ``` -------------------------------- ### Objective-C: Organizing Code with #pragma mark Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Shows how to organize Objective-C code within methods and protocol implementations using '#pragma mark -'. This enhances readability by grouping related methods under descriptive labels like 'Lifecycle', 'Event', 'Public', and 'Private'. ```objective-c #pragma mark - Lifecycle - (instancetype)init {} - (void)dealloc {} - (void)viewDidLoad {} - (void)viewWillAppear:(BOOL)animated {} - (void)didReceiveMemoryWarning {} #pragma mark - UITextFieldDelegate #pragma mark - UITableViewDataSource #pragma mark - UITableViewDelegate #pragma mark - Event - (IBAction)submitData:(id)sender {} - (void)someButtonDidPressed:(UIButton*)button #pragma mark - Public - (void)publicMethod {} #pragma mark - Private - (void)privateMethod {} #pragma mark - Setter & Getter - (void)setCustomProperty:(id)value {} - (id)customProperty {} #pragma mark - NSCopying - (id)copyWithZone:(NSZone *)zone {} #pragma mark - NSObject - (NSString *)description {} ``` -------------------------------- ### Objective-C Method Naming: Multi-Parameter Conventions Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Shows correct Objective-C method naming with multiple parameters, emphasizing descriptive keywords for each parameter to enhance readability. ```objective-c - (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; ``` ```objective-c - (void)sendAction:(SEL)aSelector toObject:(id)anObject forAllCells:(BOOL)flag; - (id)viewWithTag:(NSInteger)aTag; ``` -------------------------------- ### Objective-C Accessor Methods: Using `can`, `should`, `will` Prefixes Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Shows how to use prefixes like `can`, `should`, and `will` to convey the intent of accessor methods. It also highlights that prefixes like `do` and `does` should be avoided for method naming. ```objective-c //正确 - (void)setCanHide:(BOOL)flag; - (BOOL)canHide; - (void)setShouldCloseDocument:(BOOL)flag; - (BOOL)shouldCloseDocument; //错误,不要使用"do"或者"does" - (void)setDoesAcceptGlyphInfo:(BOOL)flag; - (BOOL)doesAcceptGlyphInfo; ``` -------------------------------- ### Objective-C Instance Variable Declaration (Recommended) Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Shows the recommended way to declare instance variables in Objective-C using a class extension within the implementation block, prefixing the variable name with an underscore (`_`). ```objective-c @implementation MyClass { BOOL _showsTitle; } ``` -------------------------------- ### Objective-C Initialization Methods with Instancetype Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Initialization methods should follow Apple's generated code templates. The return type should be `instancetype` rather than `id` to ensure proper type inference by the compiler. This applies to both designated initializers and convenience initializers. ```objc - (instancetype)init { self = [super init]; if (self) { // ... initialization logic ... } return self; } ``` -------------------------------- ### Import Framework Root Header Files (Objective-C) Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md When using frameworks, import the framework's root header file (named after the framework itself). Avoid importing individual sub-module header files. The compiler will optimize to include only necessary interfaces. ```objective-c //Correct, import root header file #import //Incorrect, do not individually import other header files within the framework #import #import ``` -------------------------------- ### Correct #import and #include Usage (Objective-C) Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Use `#import` for Objective-C or Objective-C++ header files to automatically prevent duplicate inclusions. Use `#include` for C or C++ header files, ensuring they have include guards. This distinction aids cross-platform code sharing. ```objective-c #import #include #import "GTMFoo.h" #include "base/basictypes.h" ``` -------------------------------- ### Objective-C Accessor Methods for Nouns, Adjectives, and Verbs Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Demonstrates the standard Objective-C patterns for accessor methods (getters and setters) based on whether the property is a noun, adjective, or verb. This ensures consistency in how object properties are accessed and modified. ```objective-c //属性是一个名词时的存取方法范式 - (type)noun; - (void)setNoun:(type)aNoun; //栗子 - (NSString *)title; - (void)setTitle:(NSString *)aTitle; //属性是一个形容词时存取方法的范式 - (BOOL)isAdjective; - (void)setAdjective:(BOOL)flag; //栗子 - (BOOL)isEditable; - (void)setEditable:(BOOL)flag; //属性是一个动词时存取方法的范式 - (BOOL)verbObject; - (void)setVerbObject:(BOOL)flag; //栗子 - (BOOL)showsAlpha; - (void)setShowsAlpha:(BOOL)flag; ``` -------------------------------- ### Thread-Safe Singleton Implementation (Objective-C) Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Implement singletons using a thread-safe approach to ensure proper creation of shared instances. The provided code uses `dispatch_once` for a robust and safe singleton pattern. ```objective-c + (instancetype)sharedInstance { static id sharedInstance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [[self alloc] init]; }); return sharedInstance; } ``` -------------------------------- ### Objective-C: NSNumber Syntax Sugar Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Demonstrates the use of '@' syntax sugar for creating NSNumber objects, offering a more concise way to represent primitive types and enumerated values. ```objective-c NSNumber *fortyTwo = @42; NSNumber *piOverTwo = @(M_PI / 2); enum { kMyEnum = 2; }; NSNumber *myEnum = @(kMyEnum); ``` -------------------------------- ### Objective-C Collection Operation Method Patterns Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Outlines the naming conventions for methods that manage collections of objects or elements. This includes standard methods for adding, removing, and retrieving elements, as well as methods for inserting elements at specific indices. ```objective-c //集合操作范式 - (void)addElement:(elementType)anObj; - (void)removeElement:(elementType)anObj; - (NSArray *)elements; //栗子 - (void)addLayoutManager:(NSLayoutManager *)obj; - (void)removeLayoutManager:(NSLayoutManager *)obj; - (NSArray *)layoutManagers; //如果需要将元素插入到特定的位置,使用类似于这样的命名: - (void)insertLayoutManager:(NSLayoutManager *)obj atIndex:(int)index; - (void)removeLayoutManagerAtIndex:(int)index; ``` -------------------------------- ### Objective-C Literal Syntax for Collections and Numbers Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Employ literal syntax (e.g., @[], @{}, @YES, @123) for creating NSArray, NSDictionary, and NSNumber objects. This syntax is more concise and readable than traditional alloc/init methods. Proper spacing around literals and their elements is crucial for readability, especially when spanning multiple lines. ```objc // Should: NSArray *names = @[ @"Brian", @"Matt", @"Chris", @"Alex", @"Steve", @"Paul" ]; NSDictionary *productManagers = @{ @"iPhone": @"Kate", @"iPad": @"Kamal", @"Mobile Web": @"Bill" }; NSNumber *shouldUseLiterals = @YES; NSNumber *buildingStreetNumber = @10018; // Correct spacing for multi-line literals NSArray *array = @[ @"This", @"is", @"an", @"array" ]; NSDictionary *dictionary = @{ NSFontAttributeName : [NSFont fontWithName:@"Helvetica-Bold" size:12], NSForegroundColorAttributeName : fontColor }; // Correct spacing for dictionary key-value pairs NSDictionary *option1 = @{ NSFontAttributeName : [NSFont fontWithName:@"Helvetica-Bold" size:12], NSForegroundColorAttributeName : fontColor }; // Incorrect: // 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 *buildingStreetNumber = [NSNumber numberWithInteger:10018]; ``` -------------------------------- ### Objective-C Block Formatting in Method Calls Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Shows preferred and discouraged ways to format method calls that include blocks in Objective-C. The recommended approach places blocks on the same line for readability, while colon-aligning makes block indentation difficult. ```objective-c // blocks are easily readable [UIView animateWithDuration:1.0 animations:^{ // something } completion:^(BOOL finished) { // something }]; ``` ```objective-c // colon-aligning makes the block indentation hard to read [UIView animateWithDuration:1.0 animations:^{ // something } completion:^(BOOL finished) { // something }]; ``` -------------------------------- ### Objective-C Accessor Method Naming: Active vs. Passive Voice Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Illustrates the correct and incorrect ways to name setter and getter methods in Objective-C, emphasizing the use of the active voice for setters and avoiding passive constructions for better readability and adherence to conventions. ```objective-c //正确 - (void)setAcceptsGlyphInfo:(BOOL)flag; - (BOOL)acceptsGlyphInfo; //错误,不要使用动词的被动形式 - (void)setGlyphInfoAccepted:(BOOL)flag; - (BOOL)glyphInfoAccepted; ``` -------------------------------- ### Direct Instance Variable Access in init and dealloc (Objective-C) Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Within `init` and `dealloc` methods, directly access instance variables (e.g., `_bar`) instead of using accessor methods (e.g., `self.bar`). The runtime environment is not fully established during these methods, and accessor methods can lead to unexpected behavior. ```objective-c //Correct, direct access to instance variable - (instancetype)init { self = [super init]; if (self) { _bar = [[NSMutableString alloc] init]; } return self; } - (void)dealloc { [_bar release]; [super dealloc]; } ``` ```objective-c //Incorrect, do not access via accessor methods - (instancetype)init { self = [super init]; if (self) { self.bar = [NSMutableString string]; } return self; } - (void)dealloc { self.bar = nil; [super dealloc]; } ``` -------------------------------- ### Objective-C Property Declaration (Recommended) Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Shows the recommended way to declare properties in Objective-C using the `@property` syntax within a class interface. This approach centralizes property declarations and is preferred over instance variable declarations for consistency. ```objective-c @interface RWTTutorial : NSObject @property (strong, nonatomic) NSString *tutorialName; @end ``` -------------------------------- ### Objective-C Constant Declaration (Recommended) Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Illustrates the recommended way to define string and float constants in Objective-C using `static NSString * const` and `static CGFloat const`. This approach is preferred over `#define` for better type safety and scope control. ```objective-c static NSString * const RWTAboutViewControllerCompanyName = @"RayWenderlich.com"; static CGFloat const RWTImageThumbnailHeight = 50.0; ``` -------------------------------- ### Objective-C Dot Notation for Property Access Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Use dot notation exclusively for accessing and modifying properties. Avoid using dot notation for method calls, as this can lead to readability issues. Square bracket syntax is preferred for method calls. This section also contrasts preferred dot notation usage with incorrect bracket usage for property access. ```objc // Correct: Using dot notation for property access NSString *oldName = myObject.name; myObject.name = @"Alice"; // Correct: Using bracket notation for method calls NSInteger arrayCount = [self.array count]; view.backgroundColor = [UIColor orangeColor]; [UIApplication sharedApplication].delegate; // Incorrect: Using dot notation for method calls // NSArray *array = [NSArray arrayWithObject:@"hello"]; // NSUInteger numberOfItems = array.count; // Should be [array count] // array.release; // Should be [array release] ``` -------------------------------- ### Objective-C Protocol Declaration Formatting Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Details the formatting rules for protocols in Objective-C. There should be no space between the angle brackets `<>` and the protocol or type name. This applies to all places where protocols are declared. ```objective-c @interface MyProtocoledClass : NSObject { @private id _delegate; } - (void)setDelegate:(id)aDelegate; @end ``` -------------------------------- ### Objective-C Switch Statement with Braces and Fall-through Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Demonstrates the correct usage of braces within switch case statements in Objective-C. Braces are recommended for multi-line cases and are mandatory if the compiler requires them. It also shows how to implement and comment fall-through behavior for cleaner code execution. ```objective-c switch (condition) { case 1: // ... break; case 2: { // ... // Multi-line example using braces break; } case 3: // ... break; default: // ... break; } switch (condition) { case 1: // ** fall-through! ** case 2: // code executed for values 1 and 2 break; default: // ... break; } RWTLeftMenuTopItemType menuType = RWTLeftMenuTopItemMain; switch (menuType) { case RWTLeftMenuTopItemMain: // ... break; case RWTLeftMenuTopItemShows: // ... break; case RWTLeftMenuTopItemSchedule: // ... break; } ``` -------------------------------- ### Objective-C: Using US English for Color Definitions Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Demonstrates the correct usage of US English spelling for color definitions in Objective-C. This guideline ensures consistency across the codebase, avoiding regional spelling variations. ```objective-c UIColor *myColor = [UIColor whiteColor]; ``` -------------------------------- ### Objective-C Temporary Variable Naming Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md This snippet illustrates acceptable naming for temporary variables in Objective-C. It shows that short, common abbreviations like 'i', 'k', or 'vc' are suitable for temporary variables. It also highlights that while Hungarian prefixes are acceptable for indicating purpose (e.g., 'w' for width), data types should not be used as prefixes. ```objective-c // OK wCell, vcMaster, vToolbar // 糟糕,数据类型作为前缀 bool_switchState, floatBoxHeight ``` -------------------------------- ### Objective-C Long Method Signature Formatting Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Illustrates how to format long method signatures in Objective-C by aligning parameters. When the first parameter name is short, subsequent parameters can be indented by a tab (4 spaces). ```objective-c - (id)initWithModel:(IPCModle)model ConnectType:(IPCConnectType)connectType Resolution:(IPCResolution)resolution AuthName:(NSString *)authName Password:(NSString *)password MAC:(NSString *)mac AzIp:(NSString *)az_ip AzDns:(NSString *)az_dns Token:(NSString *)token Email:(NSString *)email Delegate:(id)delegate; ``` ```objective-c - (void)short:(GTMFoo *)theFoo longKeyword:(NSRect)theRect evenLongerKeyword:(float)theInterval error:(NSError **)theError { ... ``` -------------------------------- ### Objective-C Block Formatting Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Covers various formatting rules for blocks in Objective-C based on their length. Short blocks can be on one line. For multi-line blocks, the closing brace aligns with the first non-whitespace character of the calling line. Internal code uses 4-space indentation. Large blocks should be declared as variables. ```objective-c //short block on one line [operation setCompletionBlock:^{ [self onOperationDone]; }]; //multi-line block, 4-space indent inside [operation setCompletionBlock:^{ [self.delegate newDataAvailable]; }]; //C language API block call follows same rules dispatch_async(_fileIOQueue, ^{ NSString* path = [self sessionFilePath]; if (path) { // ... } }); //long block keyword indented on new line, '}' aligns with first non-space char of calling line [[SessionService sharedService] loadWindowWithCompletionBlock:^(SessionWindow *window) { if (window) { [self windowDidLoad:window]; } else { [self errorLoadingWindow]; } }]; //long block params indented on new line [[SessionService sharedService] loadWindowWithCompletionBlock: ^(SessionWindow *window) { if (window) { [self windowDidLoad:window]; } else { [self errorLoadingWindow]; } }]; //huge block declared as variable void (^largeBlock)(void) = ^{ // ... }; [_operationQueue addOperationWithBlock:largeBlock]; //multiple blocks in one call, indented 4 spaces, not colon-aligned [myObject doSomethingWith:arg1 firstBlock:^(Foo *a) { // ... } secondBlock:^(Bar *b) { // ... }]; ``` -------------------------------- ### Objective-C Class Constructor Methods with Instancetype Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Class constructor methods (factory methods) should also return `instancetype` instead of `id`. This provides better type safety and allows the compiler to correctly deduce the return type, improving code maintainability and reducing potential runtime errors. ```objc @interface Airplane + (instancetype)airplaneWithType:(RWTAirplaneType)type; @end ``` -------------------------------- ### Objective-C Method Naming: Avoiding 'and' Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Demonstrates the incorrect use of 'and' to connect multiple parameters in Objective-C method names when they represent distinct operations. It suggests splitting such cases into separate methods. ```objective-c - (int)runModalForDirectory:(NSString *)path andFile:(NSString *)name andTypes:(NSArray *)fileTypes; - (BOOL)openFile:(NSString *)fullPath withApplication:(NSString *)appName andDeactivate:(BOOL)flag; ``` -------------------------------- ### Objective-C Conditional Statement Formatting Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Demonstrates correct and incorrect formatting for if/else statements in Objective-C. Braces should open on the same line and close on a new line. Incorrect formatting places the opening brace on a new line. ```objective-c if (user.isHappy) { //Do something } else { //Do something else } ``` ```objective-c if (user.isHappy) { //Do something } else { //Do something else } ``` -------------------------------- ### Objective-C: Nil Check Idioms Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Illustrates the correct and incorrect ways to perform nil checks in Objective-C. It emphasizes direct boolean checks over comparing with 'nil == Object'. ```objective-c // Correct, direct check if (!objc) { ... } // Incorrect, avoid nil == Object form if (nil == objc) { ... } ``` -------------------------------- ### Objective-C: Delegate Weak Reference Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Shows how to define a delegate property using 'weak' reference to prevent retain cycles. This is crucial for maintaining proper memory management when delegates are involved. ```objective-c // delegate @property (nonatomic, weak) id delegate; ``` -------------------------------- ### Objective-C Constant Declaration (Not Recommended) Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Shows the use of `#define` for defining constants, which is generally discouraged in Objective-C in favor of `const` and enums. `#define` is highlighted as being more suitable for conditional compilation directives. ```objective-c #define CompanyName @"RayWenderlich.com" #define thumbnailHeight 2; ``` -------------------------------- ### Line Break Formatting for Long Lines (Objective-C) Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md When a line of code exceeds the recommended length, break it into multiple lines. Indent the subsequent lines with two spaces for improved readability, especially for long method calls or initializations. ```objective-c self.productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers]; ``` ```objective-c self.productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productIdentifiers]; ``` -------------------------------- ### Check Return Value for Error Handling (Objective-C) Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md When a method returns an error via a reference parameter, always check the method's return value for success or failure, rather than solely inspecting the error variable. This prevents false negatives and potential crashes on success. ```objective-c NSError *error; if (![self trySomethingWithError:&error]) { // Handle Error } ``` ```objective-c NSError *error; [self trySomethingWithError:&error]; if (error) { // Handle Error } ``` -------------------------------- ### Implement Golden Path in Conditional Statements (Objective-C) Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md In conditional logic, structure your code so that the 'golden' or 'happy' path is the primary execution flow. Avoid deeply nested if statements by using multiple return statements for early exits. ```objective-c - (void)someMethod { if (![someOther boolValue]) { return; } //Do something important } ``` ```objective-c - (void)someMethod { if ([someOther boolValue]) { //Do something important } } ``` -------------------------------- ### Objective-C Notification Naming Convention Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Defines the naming convention for notifications in Objective-C, which are used for inter-module communication. The pattern is generally [ClassName][Did | Will][Action]Notification, ensuring clarity about the event being broadcast. ```objective-c NSApplicationDidBecomeActiveNotification NSWindowDidMiniaturizeNotification NSTextViewDidChangeSelectionNotification NSColorPanelColorDidChangeNotification; ``` -------------------------------- ### Use CGGeometry Functions for CGRect Access (Objective-C) Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md When accessing CGRect properties like x, y, width, or height, prefer using CGGeometry functions (e.g., CGRectGetMinX, CGRectGetWidth) over direct struct member access. These functions implicitly normalize rects, preventing potential issues. ```objective-c CGRect frame = self.view.frame; CGFloat x = CGRectGetMinX(frame); CGFloat y = CGRectGetMinY(frame); CGFloat width = CGRectGetWidth(frame); CGFloat height = CGRectGetHeight(frame); CGRect frame = CGRectMake(0.0, 0.0, width, height); ``` ```objective-c 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; CGRect frame = (CGRect){ .origin = CGPointZero, .size = frame.size }; ``` -------------------------------- ### Objective-C Property Declaration (Not Recommended) Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Illustrates a less preferred method of declaring properties in Objective-C by directly declaring instance variables within curly braces in the interface. This is generally discouraged in favor of using `@property`. ```objective-c @interface RWTTutorial : NSObject { NSString *tutorialName; } ``` -------------------------------- ### Objective-C @public and @private Declaration Formatting Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Specifies the formatting for @public and @private specifiers within Objective-C class interfaces. These specifiers should be indented with a single space. ```objective-c @interface MyClass : NSObject { @public ... @private ... } @end ``` -------------------------------- ### Use Ternary Operator for Clarity in Objective-C Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Recommends using the ternary operator `?:` in Objective-C primarily for enhancing code clarity and conciseness, especially for single conditional assignments. It advises against complex nested ternary operations, suggesting `if` statements or instance variables for multiple conditions. Parentheses improve readability when comparing non-boolean variables. ```objective-c NSInteger value = 5; result = (value != 0) ? x : y; BOOL isHorizontal = YES; result = isHorizontal ? x : y; NSArray *items; (items) ?: @[]; // Avoid: // result = a > b ? x = c > d ? c : d : y; ``` -------------------------------- ### Copy NSString on Assignment (Objective-C) Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md When assigning an `NSString` to a property or passing it as a parameter, ensure it is copied. This prevents unintended modification of the string's value by other parts of the application. ```objective-c - (void)setFoo:(NSString *)aFoo { _foo = [aFoo copy]; } ``` -------------------------------- ### Define Enums using NS_ENUM and NS_OPTIONS in Objective-C Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Defines strongly-typed enumerations using NS_ENUM and bitmask enumerations using NS_OPTIONS. These macros provide better type checking and code completion compared to traditional C-style enums. They are essential for modern Objective-C development. ```objective-c typedef NS_ENUM(NSInteger, RWTLeftMenuTopItemType) { RWTLeftMenuTopItemMain, RWTLeftMenuTopItemShows, RWTLeftMenuTopItemSchedule }; typedef NS_ENUM(NSInteger, RWTGlobalConstants) { RWTPinSizeMin = 1, RWTPinSizeMax = 5, RWTPinCountMin = 100, RWTPinCountMax = 500, }; typedef NS_OPTIONS(NSUInteger, NSWindowMask) { NSBorderlessWindowMask = 0, NSTitledWindowMask = 1 << 0, NSClosableWindowMask = 1 << 1, NSMiniaturizableWindowMask = 1 << 2, NSResizableWindowMask = 1 << 3 }; ``` -------------------------------- ### Enforce Braces in Objective-C Conditional Statements Source: https://github.com/bugs2/objective-c-coding-guidelines/blob/master/README.md Enforces the use of curly braces `{}` around the body of all conditional statements (if, else if, else) in Objective-C, even for single-line statements. This practice prevents common errors such as accidentally including subsequent lines or having commented-out lines become part of the conditional block. ```objective-c // Should: if (!error) { return success; } // Should not: if (!error) return success; // Or: if (!error) return success; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.