Objective C Nsobject Descriptive Essay

Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch. It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.

// Single-line comments start with ///*Multi-line comments look like this*/// XCode supports pragma mark directive that improve jump bar readability#pragma mark Navigation Functions // New tag on jump bar named 'Navigation Functions'#pragma mark - Navigation Functions // Same tag, now with a separator// Imports the Foundation headers with #import// Use <> to import global files (in general frameworks)// Use "" to import local files (from project)#import <Foundation/Foundation.h>#import "MyClass.h"// If you enable modules for iOS >= 7.0 or OS X >= 10.9 projects in// Xcode 5 you can import frameworks like that:@importFoundation;// Your program's entry point is a function called// main with an integer return typeintmain(intargc,constchar*argv[]){// Create an autorelease pool to manage the memory into the programNSAutoreleasePool*pool=[[NSAutoreleasePoolalloc]init];// If using automatic reference counting (ARC), use @autoreleasepool instead:@autoreleasepool{// Use NSLog to print lines to the consoleNSLog(@"Hello World!");// Print the string "Hello World!"///////////////////////////////////////// Types & Variables///////////////////////////////////////// Primitive declarationsintmyPrimitive1=1;longmyPrimitive2=234554664565;// Object declarations// Put the * in front of the variable names for strongly-typed object declarationsMyClass*myObject1=nil;// Strong typingidmyObject2=nil;// Weak typing// %@ is an object// 'description' is a convention to display the value of the ObjectsNSLog(@"%@ and %@",myObject1,[myObject2description]);// prints => "(null) and (null)"// StringNSString*worldString=@"World";NSLog(@"Hello %@!",worldString);// prints => "Hello World!"// NSMutableString is a mutable version of the NSString objectNSMutableString*mutableString=[NSMutableStringstringWithString:@"Hello"];[mutableStringappendString:@" World!"];NSLog(@"%@",mutableString);// prints => "Hello World!"// Character literalsNSNumber*theLetterZNumber=@'Z';chartheLetterZ=[theLetterZNumbercharValue];// or 'Z'NSLog(@"%c",theLetterZ);// Integral literalsNSNumber*fortyTwoNumber=@42;intfortyTwo=[fortyTwoNumberintValue];// or 42NSLog(@"%i",fortyTwo);NSNumber*fortyTwoUnsignedNumber=@42U;unsignedintfortyTwoUnsigned=[fortyTwoUnsignedNumberunsignedIntValue];// or 42NSLog(@"%u",fortyTwoUnsigned);NSNumber*fortyTwoShortNumber=[NSNumbernumberWithShort:42];shortfortyTwoShort=[fortyTwoShortNumbershortValue];// or 42NSLog(@"%hi",fortyTwoShort);NSNumber*fortyOneShortNumber=[NSNumbernumberWithShort:41];unsignedshortfortyOneUnsigned=[fortyOneShortNumberunsignedShortValue];// or 41NSLog(@"%u",fortyOneUnsigned);NSNumber*fortyTwoLongNumber=@42L;longfortyTwoLong=[fortyTwoLongNumberlongValue];// or 42NSLog(@"%li",fortyTwoLong);NSNumber*fiftyThreeLongNumber=@53L;unsignedlongfiftyThreeUnsigned=[fiftyThreeLongNumberunsignedLongValue];// or 53NSLog(@"%lu",fiftyThreeUnsigned);// Floating point literalsNSNumber*piFloatNumber=@3.141592654F;floatpiFloat=[piFloatNumberfloatValue];// or 3.141592654fNSLog(@"%f",piFloat);// prints => 3.141592654NSLog(@"%5.2f",piFloat);// prints => " 3.14"NSNumber*piDoubleNumber=@3.1415926535;doublepiDouble=[piDoubleNumberdoubleValue];// or 3.1415926535NSLog(@"%f",piDouble);NSLog(@"%4.2f",piDouble);// prints => "3.14"// NSDecimalNumber is a fixed-point class that's more precise than float or doubleNSDecimalNumber*oneDecNum=[NSDecimalNumberdecimalNumberWithString:@"10.99"];NSDecimalNumber*twoDecNum=[NSDecimalNumberdecimalNumberWithString:@"5.002"];// NSDecimalNumber isn't able to use standard +, -, *, / operators so it provides its own:[oneDecNumdecimalNumberByAdding:twoDecNum];[oneDecNumdecimalNumberBySubtracting:twoDecNum];[oneDecNumdecimalNumberByMultiplyingBy:twoDecNum];[oneDecNumdecimalNumberByDividingBy:twoDecNum];NSLog(@"%@",oneDecNum);// prints => 10.99 as NSDecimalNumber is immutable// BOOL literalsNSNumber*yesNumber=@YES;NSNumber*noNumber=@NO;// orBOOLyesBool=YES;BOOLnoBool=NO;NSLog(@"%i",yesBool);// prints => 1// Array object// May contain different data types, but must be an Objective-C objectNSArray*anArray=@[@1,@2,@3,@4];NSNumber*thirdNumber=anArray[2];NSLog(@"Third number = %@",thirdNumber);// prints => "Third number = 3"// Since Xcode 7, NSArray objects can be typed (Generics)NSArray<NSString*>*stringArray=@[@"hello",@"world"];// NSMutableArray is a mutable version of NSArray, allowing you to change// the items in the array and to extend or shrink the array object.// Convenient, but not as efficient as NSArray.NSMutableArray*mutableArray=[NSMutableArrayarrayWithCapacity:2];[mutableArrayaddObject:@"Hello"];[mutableArrayaddObject:@"World"];[mutableArrayremoveObjectAtIndex:0];NSLog(@"%@",[mutableArrayobjectAtIndex:0]);// prints => "World"// Dictionary objectNSDictionary*aDictionary=@{@"key1":@"value1",@"key2":@"value2"};NSObject*valueObject=aDictionary[@"A Key"];NSLog(@"Object = %@",valueObject);// prints => "Object = (null)"// Since Xcode 7, NSDictionary objects can be typed (Generics)NSDictionary<NSString*,NSNumber*>*numberDictionary=@{@"a":@1,@"b":@2};// NSMutableDictionary also available as a mutable dictionary objectNSMutableDictionary*mutableDictionary=[NSMutableDictionarydictionaryWithCapacity:2];[mutableDictionarysetObject:@"value1"forKey:@"key1"];[mutableDictionarysetObject:@"value2"forKey:@"key2"];[mutableDictionaryremoveObjectForKey:@"key1"];// Change types from Mutable To Immutable//In general [object mutableCopy] will make the object mutable whereas [object copy] will make the object immutableNSMutableDictionary*aMutableDictionary=[aDictionarymutableCopy];NSDictionary*mutableDictionaryChanged=[mutableDictionarycopy];// Set objectNSSet*set=[NSSetsetWithObjects:@"Hello",@"Hello",@"World",nil];NSLog(@"%@",set);// prints => {(Hello, World)} (may be in different order)// Since Xcode 7, NSSet objects can be typed (Generics)NSSet<NSString*>*stringSet=[NSSetsetWithObjects:@"hello",@"world",nil];// NSMutableSet also available as a mutable set objectNSMutableSet*mutableSet=[NSMutableSetsetWithCapacity:2];[mutableSetaddObject:@"Hello"];[mutableSetaddObject:@"Hello"];NSLog(@"%@",mutableSet);// prints => {(Hello)}///////////////////////////////////////// Operators///////////////////////////////////////// The operators works like in the C language// For example:2+5;// => 74.2f+5.1f;// => 9.3f3==2;// => 0 (NO)3!=2;// => 1 (YES)1&&1;// => 1 (Logical and)0||1;// => 1 (Logical or)~0x0F;// => 0xF0 (bitwise negation)0x0F&0xF0;// => 0x00 (bitwise AND)0x01<<1;// => 0x02 (bitwise left shift (by 1))///////////////////////////////////////// Control Structures///////////////////////////////////////// If-Else statementif(NO){NSLog(@"I am never run");}elseif(0){NSLog(@"I am also never run");}else{NSLog(@"I print");}// Switch statementswitch(2){case0:{NSLog(@"I am never run");}break;case1:{NSLog(@"I am also never run");}break;default:{NSLog(@"I print");}break;}// While loops statementsintii=0;while(ii<4){NSLog(@"%d,",ii++);// ii++ increments ii in-place, after using its value}// prints => "0,"// "1,"// "2,"// "3,"// For loops statementsintjj;for(jj=0;jj<4;jj++){NSLog(@"%d,",jj);}// prints => "0,"// "1,"// "2,"// "3,"// Foreach statementsNSArray*values=@[@0,@1,@2,@3];for(NSNumber*valueinvalues){NSLog(@"%@,",value);}// prints => "0,"// "1,"// "2,"// "3,"// Object for loop statement. Can be used with any Objective-C object typefor(iditeminvalues){NSLog(@"%@,",item);}// prints => "0,"// "1,"// "2,"// "3,"// Try-Catch-Finally statements@try{// Your statements here@throw[NSExceptionexceptionWithName:@"FileNotFoundException"reason:@"File Not Found on System"userInfo:nil];}@catch(NSException*e)// use: @catch (id exceptionName) to catch all objects.{NSLog(@"Exception: %@",e);}@finally{NSLog(@"Finally. Time to clean up.");}// prints => "Exception: File Not Found on System"// "Finally. Time to clean up."// NSError objects are useful for function arguments to populate on user mistakes.NSError*error=[NSErrorerrorWithDomain:@"Invalid email."code:4userInfo:nil];///////////////////////////////////////// Objects///////////////////////////////////////// Create an object instance by allocating memory and initializing it// An object is not fully functional until both steps have been completedMyClass*myObject=[[MyClassalloc]init];// The Objective-C model of object-oriented programming is based on message// passing to object instances// In Objective-C one does not simply call a method; one sends a message[myObjectinstanceMethodWithParameter:@"Steve Jobs"];// Clean up the memory you used into your program[pooldrain];// End of @autoreleasepool}// End the programreturn0;}///////////////////////////////////////// Classes And Functions///////////////////////////////////////// Declare your class in a header file (MyClass.h):// Class declaration syntax:// @interface ClassName : ParentClassName <ImplementedProtocols>// {// type name; <= variable declarations;// }// @property type name; <= property declarations// -/+ (type) Method declarations; <= Method declarations// @end@interfaceMyClass : NSObject<MyProtocol>// NSObject is Objective-C's base object class.{// Instance variable declarations (can exist in either interface or implementation file)intcount;// Protected access by default.@privateiddata;// Private access (More convenient to declare in implementation file)NSString*name;}// Convenient notation for public access variables to auto generate a setter method// By default, setter method name is 'set' followed by @property variable name@propertyintpropInt;// Setter method name = 'setPropInt'@property(copy)idcopyId;// (copy) => Copy the object during assignment// (readonly) => Cannot set value outside @interface@property(readonly)NSString*roString;// Use @synthesize in @implementation to create accessor// You can customize the getter and setter names instead of using default 'set' name:@property(getter=lengthGet,setter=lengthSet:)intlength;// Methods+/-(returntype)methodSignature:(ParameterType*)parameterName;// + for class methods:+(NSString*)classMethod;+(MyClass*)myClassFromHeight:(NSNumber*)defaultHeight;// - for instance methods:-(NSString*)instanceMethodWithParameter:(NSString*)string;-(NSNumber*)methodAParameterAsString:(NSString*)stringandAParameterAsNumber:(NSNumber*)number;// Constructor methods with arguments:-(id)initWithDistance:(int)defaultDistance;// Objective-C method names are very descriptive. Always name methods according to their arguments@end// States the end of the interface// To access public variables from the implementation file, @property generates a setter method// automatically. Method name is 'set' followed by @property variable name:MyClass*myClass=[[MyClassalloc]init];// create MyClass object instance[myClasssetCount:10];NSLog(@"%d",[myClasscount]);// prints => 10// Or using the custom getter and setter method defined in @interface:[myClasslengthSet:32];NSLog(@"%i",[myClasslengthGet]);// prints => 32// For convenience, you may use dot notation to set and access object instance variables:myClass.count=45;NSLog(@"%i",myClass.count);// prints => 45// Call class methods:NSString*classMethodString=[MyClassclassMethod];MyClass*classFromName=[MyClassmyClassFromName:@"Hello"];// Call instance methods:MyClass*myClass=[[MyClassalloc]init];// Create MyClass object instanceNSString*stringFromInstanceMethod=[myClassinstanceMethodWithParameter:@"Hello"];// Selectors// Way to dynamically represent methods. Used to call methods of a class, pass methods// through functions to tell other classes they should call it, and to save methods// as a variable// SEL is the data type. @selector() returns a selector from method name provided// methodAParameterAsString:andAParameterAsNumber: is method name for method in MyClassSELselectorVar=@selector(methodAParameterAsString:andAParameterAsNumber:);if([myClassrespondsToSelector:selectorVar]){// Checks if class contains method// Must put all method arguments into one object to send to performSelector functionNSArray*arguments=[NSArrayarrayWithObjects:@"Hello",@4,nil];[myClassperformSelector:selectorVarwithObject:arguments];// Calls the method}else{// NSStringFromSelector() returns a NSString of the method name of a given selectorNSLog(@"MyClass does not have method: %@",NSStringFromSelector(selectedVar));}// Implement the methods in an implementation (MyClass.m) file:@implementationMyClass{longdistance;// Private access instance variableNSNumberheight;}// To access a public variable from the interface file, use '_' followed by variable name:_count=5;// References "int count" from MyClass interface// Access variables defined in implementation file:distance=18;// References "long distance" from MyClass implementation// To use @property variable in implementation, use @synthesize to create accessor variable:@synthesizeroString=_roString;// _roString available now in @implementation// Called before calling any class methods or instantiating any objects+(void)initialize{if(self==[MyClassclass]){distance=0;}}// Counterpart to initialize method. Called when an object's reference count is zero-(void)dealloc{[heightrelease];// If not using ARC, make sure to release class variable objects[superdealloc];// and call parent class dealloc}// Constructors are a way of creating instances of a class// This is a default constructor which is called when the object is initialized.-(id)init{if((self=[superinit]))// 'super' used to access methods from parent class{self.count=1;// 'self' used for object to call itself}returnself;}// Can create constructors that contain arguments:-(id)initWithDistance:(int)defaultDistance{distance=defaultDistance;returnself;}+(NSString*)classMethod{return@"Some string";}+(MyClass*)myClassFromHeight:(NSNumber*)defaultHeight{height=defaultHeight;return[[selfalloc]init];}-(NSString*)instanceMethodWithParameter:(NSString*)string{return@"New string";}-(NSNumber*)methodAParameterAsString:(NSString*)stringandAParameterAsNumber:(NSNumber*)number{return@42;}// Objective-C does not have private method declarations, but you can simulate them.// To simulate a private method, create the method in the @implementation but not in the @interface.-(NSNumber*)secretPrivateMethod{return@72;}[selfsecretPrivateMethod];// Calls private method// Methods declared into MyProtocol-(void)myProtocolMethod{// statements}@end// States the end of the implementation///////////////////////////////////////// Categories///////////////////////////////////////// A category is a group of methods designed to extend a class. They allow you to add new methods// to an existing class for organizational purposes. This is not to be mistaken with subclasses.// Subclasses are meant to CHANGE functionality of an object while categories instead ADD// functionality to an object.// Categories allow you to:// -- Add methods to an existing class for organizational purposes.// -- Allow you to extend Objective-C object classes (ex: NSString) to add your own methods.// -- Add ability to create protected and private methods to classes.// NOTE: Do not override methods of the base class in a category even though you have the ability// to. Overriding methods may cause compiler errors later between different categories and it// ruins the purpose of categories to only ADD functionality. Subclass instead to override methods.// Here is a simple Car base class.@interfaceCar : NSObject@propertyNSString*make;@propertyNSString*color;-(void)turnOn;-(void)accelerate;@end// And the simple Car base class implementation:#import "Car.h"@implementationCar@synthesizemake=_make;@synthesizecolor=_color;-(void)turnOn{NSLog(@"Car is on.");}-(void)accelerate{NSLog(@"Accelerating.");}@end// Now, if we wanted to create a Truck object, we would instead create a subclass of Car as it would// be changing the functionality of the Car to behave like a truck. But lets say we want to just add// functionality to this existing Car. A good example would be to clean the car. So we would create// a category to add these cleaning methods:// @interface filename: Car+Clean.h (BaseClassName+CategoryName.h)#import "Car.h" // Make sure to import base class to extend.@interfaceCar(Clean)// The category name is inside () following the name of the base class.-(void)washWindows;// Names of the new methods we are adding to our Car object.-(void)wax;@end// @implementation filename: Car+Clean.m (BaseClassName+CategoryName.m)#import "Car+Clean.h" // Import the Clean category's @interface file.@implementationCar(Clean)-(void)washWindows{NSLog(@"Windows washed.");}-(void)wax{NSLog(@"Waxed.");}@end// Any Car object instance has the ability to use a category. All they need to do is import it:#import "Car+Clean.h" // Import as many different categories as you want to use.#import "Car.h" // Also need to import base class to use it's original functionality.intmain(intargc,constchar*argv[]){@autoreleasepool{Car*mustang=[[Caralloc]init];mustang.color=@"Red";mustang.make=@"Ford";[mustangturnOn];// Use methods from base Car class.[mustangwashWindows];// Use methods from Car's Clean category.}return0;}// Objective-C does not have protected method declarations but you can simulate them.// Create a category containing all of the protected methods, then import it ONLY into the// @implementation file of a class belonging to the Car class:@interfaceCar(Protected)// Naming category 'Protected' to remember methods are protected.-(void)lockCar;// Methods listed here may only be created by Car objects.@end//To use protected methods, import the category, then implement the methods:#import "Car+Protected.h" // Remember, import in the @implementation file only.@implementationCar-(void)lockCar{NSLog(@"Car locked.");// Instances of Car can't use lockCar because it's not in the @interface.}@end///////////////////////////////////////// Extensions///////////////////////////////////////// Extensions allow you to override public access property attributes and methods of an @interface.// @interface filename: Shape.h@interfaceShape : NSObject// Base Shape class extension overrides below.@property(readonly)NSNumber*numOfSides;-(int)getNumOfSides;@end// You can override numOfSides variable or getNumOfSides method to edit them with an extension:// @implementation filename: Shape.m#import "Shape.h"// Extensions live in the same file as the class @implementation.@interfaceShape()// () after base class name declares an extension.@property(copy)NSNumber*numOfSides;// Make numOfSides copy instead of readonly.-(NSNumber)getNumOfSides;// Make getNumOfSides return a NSNumber instead of an int.-(void)privateMethod;// You can also create new private methods inside of extensions.@end// The main @implementation:@implementationShape@synthesizenumOfSides=_numOfSides;-(NSNumber)getNumOfSides{// All statements inside of extension must be in the @implementation.return_numOfSides;}-(void)privateMethod{NSLog(@"Private method created by extension. Shape instances cannot call me.");}@end// Starting in Xcode 7.0, you can create Generic classes,// allowing you to provide greater type safety and clarity// without writing excessive boilerplate.@interfaceResult<__covariantA>:NSObject-(void)handleSuccess:(void(^)(A))successfailure:(void(^)(NSError*))failure;@property(nonatomic)Aobject;@end// we can now declare instances of this class likeResult<NSNumber*>*result;Result<NSArray*>*result;// Each of these cases would be equivalent to rewriting Result's interface// and substituting the appropriate type for A@interfaceResult : NSObject-(void)handleSuccess:(void(^)(NSArray*))successfailure:(void(^)(NSError*))failure;@property(nonatomic)NSArray*object;@end@interfaceResult : NSObject-(void)handleSuccess:(void(^)(NSNumber*))successfailure:(void(^)(NSError*))failure;@property(nonatomic)NSNumber*object;@end// It should be obvious, however, that writing one// Class to solve a problem is always preferable to writing two// Note that Clang will not accept generic types in @implementations,// so your @implemnation of Result would have to look like this:@implementationResult-(void)handleSuccess:(void(^)(id))successfailure:(void(^)(NSError*))failure{// Do something}@end///////////////////////////////////////// Protocols///////////////////////////////////////// A protocol declares methods that can be implemented by any class.// Protocols are not classes themselves. They simply define an interface// that other objects are responsible for implementing.// @protocol filename: "CarUtilities.h"@protocolCarUtilities<NSObject>// <NSObject> => Name of another protocol this protocol includes.@propertyBOOLengineOn;// Adopting class must @synthesize all defined @properties and-(void)turnOnEngine;// all defined methods.@end// Below is an example class implementing the protocol.#import "CarUtilities.h" // Import the @protocol file.@interfaceCar : NSObject<CarUtilities>// Name of protocol goes inside <>// You don't need the @property or method names here for CarUtilities. Only @implementation does.-(void)turnOnEngineWithUtilities:(id<CarUtilities>)car;// You can use protocols as data too.@end// The @implementation needs to implement the @properties and methods for the protocol.@implementationCar : NSObject<CarUtilities>@synthesizeengineOn=_engineOn;// Create a @synthesize statement for the engineOn @property.-(void)turnOnEngine{// Implement turnOnEngine however you would like. Protocols do not define_engineOn=YES;// how you implement a method, it just requires that you do implement it.}// You may use a protocol as data as you know what methods and variables it has implemented.-(void)turnOnEngineWithCarUtilities:(id<CarUtilities>)objectOfSomeKind{[objectOfSomeKindengineOn];// You have access to object variables[objectOfSomeKindturnOnEngine];// and the methods inside.[objectOfSomeKindengineOn];// May or may not be YES. Class implements it however it wants.}@end// Instances of Car now have access to the protocol.Car*carInstance=[[Caralloc]init];[carInstancesetEngineOn:NO];[carInstanceturnOnEngine];if([carInstanceengineOn]){NSLog(@"Car engine is on.");// prints => "Car engine is on."}// Make sure to check if an object of type 'id' implements a protocol before calling protocol methods:if([myClassconformsToProtocol:@protocol(CarUtilities)]){NSLog(@"This does not run as the MyClass class does not implement the CarUtilities protocol.");}elseif([carInstanceconformsToProtocol:@protocol(CarUtilities)]){NSLog(@"This does run as the Car class implements the CarUtilities protocol.");}// Categories may implement protocols as well: @interface Car (CarCategory) <CarUtilities>// You may implement many protocols: @interface Car : NSObject <CarUtilities, CarCleaning>// NOTE: If two or more protocols rely on each other, make sure to forward-declare them:#import "Brother.h"@protocolBrother; // Forward-declare statement. Without it, compiler will throw error.@protocolSister<NSObject>-(void)beNiceToBrother:(id<Brother>)brother;@end// See the problem is that Sister relies on Brother, and Brother relies on Sister.#import "Sister.h"@protocolSister; // These lines stop the recursion, resolving the issue.@protocolBrother<NSObject>-(void)beNiceToSister:(id<Sister>)sister;@end///////////////////////////////////////// Blocks///////////////////////////////////////// Blocks are statements of code, just like a function, that are able to be used as data.// Below is a simple block with an integer argument that returns the argument plus 4.int(^addUp)(intn);// Declare a variable to store the block.void(^noParameterBlockVar)(void);// Example variable declaration of block with no arguments.// Blocks have access to variables in the same scope. But the variables are readonly and the// value passed to the block is the value of the variable when the block is created.intoutsideVar=17;// If we edit outsideVar after declaring addUp, outsideVar is STILL 17.__blocklongmutableVar=3;// __block makes variables writable to blocks, unlike outsideVar.addUp=^(intn){// Remove (int n) to have a block that doesn't take in any parameters.NSLog(@"You may have as many lines in a block as you would like.");NSSet*blockSet;// Also, you can declare local variables.mutableVar=32;// Assigning new value to __block variable.returnn+outsideVar;// Return statements are optional.}intaddUp=addUp(10+16);// Calls block code with arguments.// Blocks are often used as arguments to functions to be called later, or for callbacks.@implementationBlockExample : NSObject-(void)runBlock:(void(^)(NSString))block{NSLog(@"Block argument returns nothing and takes in a NSString object.");block(@"Argument given to block to execute.");// Calling block.}@end///////////////////////////////////////// Memory Management////////////////////////////////////////*For each object used in an application, memory must be allocated for that object. When the applicationis done using that object, memory must be deallocated to ensure application efficiency.Objective-C does not use garbage collection and instead uses reference counting. As long asthere is at least one reference to an object (also called "owning" an object), then the objectwill be available to use (known as "ownership").When an instance owns an object, its reference counter is increments by one. When theobject is released, the reference counter decrements by one. When reference count is zero,the object is removed from memory.With all object interactions, follow the pattern of:(1) create the object, (2) use the object, (3) then free the object from memory.*/MyClass*classVar=[MyClassalloc];// 'alloc' sets classVar's reference count to one. Returns pointer to object[classVarrelease];// Decrements classVar's reference count// 'retain' claims ownership of existing object instance and increments reference count. Returns pointer to objectMyClass*newVar=[classVarretain];// If classVar is released, object is still in memory because newVar is owner[classVarautorelease];// Removes ownership of object at end of @autoreleasepool block. Returns pointer to object// @property can use 'retain' and 'assign' as well for small convenient definitions@property(retain)MyClass*instance;// Release old value and retain a new one (strong reference)@property(assign)NSSet*set;// Pointer to new value without retaining/releasing old (weak reference)// Automatic Reference Counting (ARC)// Because memory management can be a pain, Xcode 4.2 and iOS 4 introduced Automatic Reference Counting (ARC).// ARC is a compiler feature that inserts retain, release, and autorelease automatically for you, so when using ARC,// you must not use retain, release, or autoreleaseMyClass*arcMyClass=[[MyClassalloc]init];// ... code using arcMyClass// Without ARC, you will need to call: [arcMyClass release] after you're done using arcMyClass. But with ARC,// there is no need. It will insert this release statement for you// As for the 'assign' and 'retain' @property attributes, with ARC you use 'weak' and 'strong'@property(weak)MyClass*weakVar;// 'weak' does not take ownership of object. If original instance's reference count// is set to zero, weakVar will automatically receive value of nil to avoid application crashing@property(strong)MyClass*strongVar;// 'strong' takes ownership of object. Ensures object will stay in memory to use// For regular variables (not @property declared variables), use the following:__strongNSString*strongString;// Default. Variable is retained in memory until it leaves it's scope__weakNSSet*weakSet;// Weak reference to existing object. When existing object is released, weakSet is set to nil__unsafe_unretainedNSArray*unsafeArray;// Like __weak, but unsafeArray not set to nil when existing object is released

Further Reading

Wikipedia Objective-C

Programming with Objective-C. Apple PDF book

Programming with Objective-C for iOS

Programming with Objective-C for Mac OSX

iOS For High School Students: Getting Started


Got a suggestion? A correction, perhaps? Open an Issue on the Github Repo, or make a pull request yourself!

Originally contributed by Eugene Yagrushkin, and updated by 17 contributor(s).

© 2018 Eugene Yagrushkin, Yannick Loriot, Levi Bostian, Clayton Walker, Fernando Valverde

styleguide

Google Objective-C Style Guide

Objective-C is a dynamic, object-oriented extension of C. It’s designed to be easy to use and read, while enabling sophisticated object-oriented design. It is the primary development language for applications on OS X and on iOS.

Apple has already written a very good, and widely accepted, Cocoa Coding Guidelines for Objective-C. Please read it in addition to this guide.

The purpose of this document is to describe the Objective-C (and Objective-C++) coding guidelines and practices that should be used for iOS and OS X code. These guidelines have evolved and been proven over time on other projects and teams. Open-source projects developed by Google conform to the requirements in this guide.

Note that this guide is not an Objective-C tutorial. We assume that the reader is familiar with the language. If you are new to Objective-C or need a refresher, please read Programming with Objective-C.

Principles

Optimize for the reader, not the writer

Codebases often have extended lifetimes and more time is spent reading the code than writing it. We explicitly choose to optimize for the experience of our average software engineer reading, maintaining, and debugging code in our codebase rather than the ease of writing said code. For example, when something surprising or unusual is happening in a snippet of code, leaving textual hints for the reader is valuable.

Be consistent

When the style guide allows multiple options it is preferable to pick one option over mixed usage of multiple options. Using one style consistently throughout a codebase lets engineers focus on other (more important) issues. Consistency also enables better automation because consistent code allows more efficient development and operation of tools that format or refactor code. In many cases, rules that are attributed to “Be Consistent” boil down to “Just pick one and stop worrying about it”; the potential value of allowing flexibility on these points is outweighed by the cost of having people argue over them.

Be consistent with Apple SDKs

Consistency with the way Apple SDKs use Objective-C has value for the same reasons as consistency within our code base. If an Objective-C feature solves a problem that’s an argument for using it. However, sometimes language features and idioms are flawed, or were just designed with assumptions that are not universal. In those cases it is appropriate to constrain or ban language features or idioms.

Style rules should pull their weight

The benefit of a style rule must be large enough to justify asking engineers to remember it. The benefit is measured relative to the codebase we would get without the rule, so a rule against a very harmful practice may still have a small benefit if people are unlikely to do it anyway. This principle mostly explains the rules we don’t have, rather than the rules we do: for example, goto contravenes many of the following principles, but is not discussed due to its extreme rarity.

Example

They say an example is worth a thousand words, so let’s start off with an example that should give you a feel for the style, spacing, naming, and so on.

Here is an example header file, demonstrating the correct commenting and spacing for an declaration.

An example source file, demonstrating the correct commenting and spacing for the of an interface.

Spacing and Formatting

Spaces vs. Tabs

Use only spaces, and indent 2 spaces at a time. We use spaces for indentation. Do not use tabs in your code.

You should set your editor to emit spaces when you hit the tab key, and to trim trailing spaces on lines.

Line Length

The maximum line length for Objective-C files is 100 columns.

You can make violations easier to spot by enabling Preferences > Text Editing > Page guide at column: 100 in Xcode.

Method Declarations and Definitions

One space should be used between the or and the return type, and no spacing in the parameter list except between parameters.

Methods should look like this:

The spacing before the asterisk is optional. When adding new code, be consistent with the surrounding file’s style.

If you have too many parameters to fit on one line, giving each its own line is preferred. If multiple lines are used, align each using the colon before the parameter.

When the second or later parameter name is longer than the first, indent the second and later lines by at least four spaces, maintaining colon alignment:

Conditionals

Include a space after , , , and , and around comparison operators.

Braces may be omitted when a loop body or conditional statement fits on a single line.

If an clause has an clause, both clauses should use braces.

Intentional fall-through to the next case should be documented with a comment unless the case has no intervening code before the next case.

Expressions

Use a space around binary operators and assignments. Omit a space for a unary operator. Do not add spaces inside parentheses.

Factors in an expression may omit spaces.

Method Invocations

Method invocations should be formatted much like method declarations.

When there’s a choice of formatting styles, follow the convention already used in a given source file. Invocations should have all arguments on one line:

or have one argument per line, with colons aligned:

Don’t use any of these styles:

As with declarations and definitions, when the first keyword is shorter than the others, indent the later lines by at least four spaces, maintaining colon alignment:

Invocations containing multiple inlined blocks may have their parameter names left-aligned at a four space indent.

Function Calls

Function calls should include as many parameters as fit on each line, except where shorter lines are needed for clarity or documentation of the parameters.

Continuation lines for function parameters may be indented to align with the opening parenthesis, or may have a four-space indent.

Use local variables with descriptive names to shorten function calls and reduce nesting of calls.

Exceptions

Format exceptions with and labels on the same line as the preceding . Add a space between the label and the opening brace (), as well as between the and the caught object declaration. If you must use Objective-C exceptions, format them as follows. However, see Avoid Throwing Exceptions for reasons why you should not be using exceptions.

Function Length

Prefer small and focused functions.

Long functions and methods are occasionally appropriate, so no hard limit is placed on function length. If a function exceeds about 40 lines, think about whether it can be broken up without harming the structure of the program.

Even if your long function works perfectly now, someone modifying it in a few months may add new behavior. This could result in bugs that are hard to find. Keeping your functions short and simple makes it easier for other people to read and modify your code.

When updating legacy code, consider also breaking long functions into smaller and more manageable pieces.

Vertical Whitespace

Use vertical whitespace sparingly.

To allow more code to be easily viewed on a screen, avoid putting blank lines just inside the braces of functions.

Limit blank lines to one or two between functions and between logical groups of code.

Naming

Names should be as descriptive as possible, within reason. Follow standard Objective-C naming rules.

Avoid non-standard abbreviations. Don’t worry about saving horizontal space as it is far more important to make your code immediately understandable by a new reader. For example:

Any class, category, method, function, or variable name should use all capitals for acronyms and initialisms within the name. This follows Apple’s standard of using all capitals within a name for acronyms such as URL, ID, TIFF, and EXIF.

Names of C functions and typedefs should be capitalized and use camel case as appropriate for the surrounding code.

File Names

File names should reflect the name of the class implementation that they contain—including case.

Follow the convention that your project uses. File extensions should be as follows:

ExtensionType
.hC/C++/Objective-C header file
.mObjective-C implementation file
.mmObjective-C++ implementation file
.ccPure C++ implementation file
.cC implementation file

Files containing code that may be shared across projects or used in a large project should have a clearly unique name, typically including the project or class prefix.

File names for categories should include the name of the class being extended, like GTMNSString+Utils.h or NSTextView+GTMAutocomplete.h

Class Names

Class names (along with category and protocol names) should start as uppercase and use mixed case to delimit words.

When designing code to be shared across multiple applications, prefixes are acceptable and recommended (e.g. GTMSendMessage). Prefixes are also recommended for classes of large applications that depend on external libraries.

Category Names

Category names should start with a 3 character prefix identifying the category as part of a project or open for general use.

The category name should incorporate the name of the class it’s extending. For example, if we want to create a category on for parsing, we would put the category in a file named , and the category itself would be named . The file name and the category may not match, as this file could have many separate categories related to parsing. Methods in that category should share the prefix () in order to prevent collisions in Objective-C’s global namespace.

There should be a single space between the class name and the opening parenthesis of the category.

Objective-C Method Names

Method and parameter names typically start as lowercase and then use mixed case.

Proper capitalization should be respected, including at the beginning of names.

The method name should read like a sentence if possible, meaning you should choose parameter names that flow with the method name. Objective-C method names tend to be very long, but this has the benefit that a block of code can almost read like prose, thus rendering many implementation comments unnecessary.

Use prepositions and conjunctions like “with”, “from”, and “to” in the second and later parameter names only where necessary to clarify the meaning or behavior of the method.

A method that returns an object should have a name beginning with a noun identifying the object returned:

An accessor method should be named the same as the object it’s getting, but it should not be prefixed with the word . For example:

Accessors that return the value of boolean adjectives have method names beginning with , but property names for those methods omit the .

Dot notation is used only with property names, not with method names.

See Apple’s Guide to Naming Methods for more details on Objective-C naming.

These guidelines are for Objective-C methods only. C++ method names continue to follow the rules set in the C++ style guide.

Function Names

Regular functions have mixed case.

Ordinarily, functions should start with a capital letter and have a capital letter for each new word (a.k.a. “Camel Case” or “Pascal case”).

Because Objective-C does not provide namespacing, non-static functions should have a prefix that minimizes the chance of a name collision.

Variable Names

Variable names typically start with a lowercase and use mixed case to delimit words.

Instance variables have leading underscores. File scope or global variables have a prefix . For example: , , .

Common Variable Names

Readers should be able to infer the variable type from the name, but do not use Hungarian notation for syntactic attributes, such as the static type of a variable (int or pointer).

File scope or global variables (as opposed to constants) declared outside the scope of a method or function should be rare, and should have the prefix g.

Instance Variables

Instance variable names are mixed case and should be prefixed with an underscore, like .

NOTE: Google’s previous convention for Objective-C ivars was a trailing underscore. Existing projects may opt to continue using trailing underscores in new code in order to maintain consistency within the project codebase. Consistency of prefix or suffix underscores should be maintained within each class.

Constants

Constant symbols (const global and static variables and constants created with #define) should use mixed case to delimit words.

Global and file scope constants should have an appropriate prefix.

Because Objective-C does not provide namespacing, constants with external linkage should have a prefix that minimizes the chance of a name collision, typically like or .

For interoperability with Swift code, enumerated values should have names that extend the typedef name:

Constants may use a lowercase k prefix when appropriate:

Types and Declarations

Local Variables

Declare variables in the narrowest practical scopes, and close to their use. Initialize variables in their declarations.

Occasionally, efficiency will make it more appropriate to declare a variable outside the scope of its use. This example declares meters separate from initialization, and needlessly sends the lastKnownLocation message each time through the loop:

Under Automatic Reference Counting, pointers to Objective-C objects are by default initialized to , so explicit initialization to is not required.

Unsigned Integers

Avoid unsigned integers except when matching types used by system interfaces.

Subtle errors crop up when doing math or counting down to zero using unsigned integers. Rely only on signed integers in math expressions except when matching NSUInteger in system interfaces.

Unsigned integers may be used for flags and bitmasks, though often NS_OPTIONS or NS_ENUM will be more appropriate.

Types with Inconsistent Sizes

Due to sizes that differ in 32- and 64-bit builds, avoid types long, NSInteger, NSUInteger, and CGFloat except when matching system interfaces.

Types long, NSInteger, NSUInteger, and CGFloat vary in size between 32- and 64-bit builds. Use of these types is appropriate when handling values exposed by system interfaces, but they should be avoided for most other computations.

File and buffer sizes often exceed 32-bit limits, so they should be declared using , not with , , or .

Comments are absolutely vital to keeping our code readable. The following rules describe what you should comment and where. But remember: while comments are important, the best code is self-documenting. Giving sensible names to types and variables is much better than using obscure names and then trying to explain them through comments.

Pay attention to punctuation, spelling, and grammar; it is easier to read well-written comments than badly written ones.

Comments should be as readable as narrative text, with proper capitalization and punctuation. In many cases, complete sentences are more readable than sentence fragments. Shorter comments, such as comments at the end of a line of code, can sometimes be less formal, but use a consistent style. When writing your comments, write for your audience: the next contributor who will need to understand your code. Be generous—the next one may be you!

A file may optionally start with a description of its contents. Every file may contain the following items, in order:

  • License boilerplate if necessary. Choose the appropriate boilerplate for the license used by the project.
  • A basic description of the contents of the file if necessary.

If you make significant changes to a file with an author line, consider deleting the author line since revision history already provides a more detailed and accurate record of authorship.

Every non-trivial interface, public and private, should have an accompanying comment describing its purpose and how it fits into the larger picture.

Comments should be used to document classes, properties, ivars, functions, categories, protocol declarations, and enums.

Doxygen-style comments are encouraged for interfaces as they are parsed by Xcode to display formatted documentation. There is a wide variety of Doxygen commands; use them consistently within a project.

If you have already described an interface in detail in the comments at the top of your file, feel free to simply state, “See comment at top of file for a complete description”, but be sure to have some sort of comment.

Additionally, each method should have a comment explaining its function, arguments, return value, thread or queue assumptions, and any side effects. Documentation comments should be in the header for public methods, or immediately preceding the method for non-trivial private methods.

Use descriptive form (“Opens the file”) rather than imperative form (“Open the file”) for method and function comments. The comment describes the function; it does not tell the function what to do.

Document the thread usage assumptions the class, properties, or methods make, if any. If an instance of the class can be accessed by multiple threads, take extra care to document the rules and invariants surrounding multithreaded use.

Any sentinel values for properties and ivars, such as or , should be documented in comments.

Declaration comments explain how a method or function is used. Comments explaining how a method or function is implemented should be with the implementation rather than with the declaration.

Provide comments explaining tricky, subtle, or complicated sections of code.

When useful, also provide comments about implementation approaches that were considered or abandoned.

End-of-line comments should be separated from the code by at least 2 spaces. If you have several comments on subsequent lines, it can often be more readable to line them up.

Disambiguating Symbols

Where needed to avoid ambiguity, use backticks or vertical bars to quote variable names and symbols in comments in preference to using quotation marks or naming the symbols inline.

In Doxygen-style comments, prefer demarcating symbols with a monospace text command, such as .

Demarcation helps provide clarity when a symbol is a common word that might make the sentence read like it was poorly constructed. A common example is the symbol :

or when quoting something which already contains quotes

Backticks or vertical bars are not needed when a symbol is self-apparent.

Doxygen formatting is also suitable for identifying symbols.

Object Ownership

For objects not managed by ARC, make the pointer ownership model as explicit as possible when it falls outside the most common Objective-C usage idioms.

Manual Reference Counting

Instance variables for NSObject-derived objects are presumed to be retained; if they are not retained, they should be either commented as weak or declared with the lifetime qualifier.

An exception is in Mac software for instance variables labeled as , which are presumed to not be retained.

Where instance variables are pointers to Core Foundation, C++, and other non-Objective-C objects, they should always be declared with strong and weak comments to indicate which pointers are and are not retained. Core Foundation and other non-Objective-C object pointers require explicit memory management, even when building for automatic reference counting.

Examples of strong and weak declarations:

Automatic Reference Counting

Object ownership and lifetime are explicit when using ARC, so no additional comments are required for automatically retained objects.

C Language Features

Macros

Avoid macros, especially where variables, enums, XCode snippets, or C functions may be used instead.

Macros make the code you see different from the code the compiler sees. Modern C renders traditional uses of macros for constants and utility functions unnecessary. Macros should only be used when there is no other solution available.

Where a macro is needed, use a unique name to avoid the risk of a symbol collision in the compilation unit. If practical, keep the scope limited by the macro after its use.

Macro names should use —all uppercase letters with underscores between words. Function-like macros may use C function naming practices. Do not define macros that appear to be C or Objective-C keywords.

Avoid macros that expand to unbalanced C or Objective-C constructs. Avoid macros that introduce scope, or may obscure the capturing of values in blocks.

Avoid macros that generate class, property, or method definitions in headers to be used as public API. These only make the code hard to understand, and the language already has better ways of doing this.

Avoid macros that generate method implementations, or that generate declarations of variables that are later used outside of the macro. Macros shouldn’t make code hard to understand by hiding where and how a variable is declared.

Examples of acceptable macro use include assertion and debug logging macros that are conditionally compiled based on build settings—often, these are not compiled into release builds.

Nonstandard Extensions

Nonstandard extensions to C/Objective-C may not be used unless otherwise specified.

Compilers support various extensions that are not part of standard C. Examples include compound statement expressions (e.g. and variable-length arrays.

is an approved exception, as it is used in Objective-C API specifications.

The binary form of the conditional operator, , is an approved exception.

Cocoa and Objective-C Features

Identify Designated Initializer

Clearly identify your designated initializer.

It is important for those who might be subclassing your class that the designated initializer be clearly identified. That way, they only need to override a single initializer (of potentially several) to guarantee the initializer of their subclass is called. It also helps those debugging your class in the future understand the flow of initialization code if they need to step through it. Identify the designated initializer using comments or the macro. If you use , mark unsupported initializers with .

Override Designated Initializer

When writing a subclass that requires an method, make sure you override the designated initializer of the superclass.

If you fail to override the designated initializer of the superclass, your initializer may not be called in all cases, leading to subtle and very difficult to find bugs.

Overridden NSObject Method Placement

Put overridden methods of NSObject at the top of an .

This commonly applies to (but is not limited to) the , , and methods. The methods should be grouped together, followed by other typical methods such as , , and .

Convenience class factory methods for creating instances may precede the methods.

Initialization

Don’t initialize instance variables to or in the method; doing so is redundant.

All instance variables for a newly allocated object are initialized to (except for isa), so don’t clutter up the init method by re-initializing variables to or .

Instance variables should typically be declared in implementation files or auto-synthesized by properties. When ivars are declared in a header file, they should be marked or .

Avoid +new

Do not invoke the class method , nor override it in a subclass. Instead, use and methods to instantiate retained objects.

Modern Objective-C code explicitly calls and an method to create and retain an object. As the class method is rarely used, it makes reviewing code for correct memory management more difficult.

Keep the Public API Simple

Keep your class simple; avoid “kitchen-sink” APIs. If a method doesn’t need to be public, keep it out of the public interface.

Unlike C++, Objective-C doesn’t differentiate between public and private methods; any message may be sent to an object. As a result, avoid placing methods in the public API unless they are actually expected to be used by a consumer of the class. This helps reduce the likelihood they’ll be called when you’re not expecting it. This includes methods that are being overridden from the parent class.

Since internal methods are not really private, it’s easy to accidentally override a superclass’s “private” method, thus making a very difficult bug to squash. In general, private methods should have a fairly unique name that will prevent subclasses from unintentionally overriding them.

#import and #include

Objective-C and Objective-C++ headers, and C/C++ headers.

Choose between and based on the language of the header that you are including.

When including a header that uses Objective-C or Objective-C++, use . When including a standard C or C++ header, use . The header should provide its own guard.

Order of Includes

The standard order for header inclusion is the related header, operating system headers, language library headers, and finally groups of headers for other dependencies.

The related header precedes others to ensure it has no hidden dependencies. For implementation files the related header is the header file. For test files the related header is the header containing the tested interface.

A blank line may separate logically distinct groups of included headers.

Import headers using their path relative to the project’s source directory.

Import umbrella headers for system frameworks and system libraries rather than include individual files.

While it may seem tempting to include individual system headers from a framework such as Cocoa or Foundation, in fact it’s less work on the compiler if you include the top-level root framework. The root framework is generally pre-compiled and can be loaded much more quickly. In addition, remember to use or rather than for Objective-C frameworks.

Avoid Messaging the Current Object Within Initializers and

Code in initializers and should avoid invoking instance methods.

Superclass initialization completes before subclass initialization. Until all classes have had a chance to initialize their instance state any method invocation on self may lead to a subclass operating on uninitialized instance state.

A similar issue exists for , where a method invocation may cause a class to operate on state that has been deallocated.

One case where this is less obvious is property accessors. These can be overridden just like any other selector. Whenever practical, directly assign to and release ivars in initializers and , rather than rely on accessors.

Beware of factoring common initialization code into helper methods:

  • Methods can be overridden in subclasses, either deliberately, or accidentally due to naming collisions.
  • When editing a helper method, it may not be obvious that the code is being run from an initializer.

Setters copy NSStrings

Setters taking an should always copy the string it accepts. This is often also appropriate for collections like and .

Never just retain the string, as it may be a . This avoids the caller changing it under you without your knowledge.

Code receiving and holding collection objects should also consider that the passed collection may be mutable, and thus the collection could be more safely held as a copy or mutable copy of the original.

Use Lightweight Generics to Document Contained Types

All projects compiling on Xcode 7 or newer versions should make use of the Objective-C lightweight generics notation to type contained objects.

Every , , or reference should be declared using lightweight generics for improved type safety and to explicitly document usage.

If the fully-annotated types become complex, consider using a typedef to preserve readability.

Use the most descriptive common superclass or protocol available. In the most generic case when nothing else is known, declare the collection to be explicitly heterogenous using id.

Avoid Throwing Exceptions

Don’t Objective-C exceptions, but you should be prepared to catch them from third-party or OS calls.

This follows the recommendation to use error objects for error delivery in Apple’s Introduction to Exception Programming Topics for Cocoa.

We do compile with (mainly so we get ), but we don’t . Use of , , and are allowed when required to properly use 3rd party code or libraries. If you do use them, please document exactly which methods you expect to throw.

Checks

Use checks for logic flow only.

Use pointer checks for logic flow of the application, not for preventing crashes when sending messages. Sending a message to reliably returns as a pointer, zero as an integer or floating-point value, structs initialized to , and values equal to .

Note that this applies to as a message target, not as a parameter value. Individual methods may or may not safely handle parameter values.

Note too that this is distinct from checking C/C++ pointers and block pointers against , which the runtime does not handle and will cause your application to crash. You still need to make sure you do not dereference a pointer.

BOOL Pitfalls

Be careful when converting general integral values to . Avoid comparing directly with .

in OS X and in 32-bit iOS builds is defined as a signed , so it may have values other than () and (). Do not cast or convert general integral values directly to .

Common mistakes include casting or converting an array’s size, a pointer value, or the result of a bitwise logic operation to a that could, depending on the value of the last byte of the integer value, still result in a value. When converting a general integral value to a use ternary operators to return a or value.

You can safely interchange and convert , and (see C++ Std 4.7.4, 4.12 and C99 Std 6.3.1.2). Use in Objective-C method signatures.

Using logical operators (, and ) with is also valid and will return values that can be safely converted to without the need for a ternary operator.

Also, don’t directly compare variables directly with . Not only is it harder to read for those well-versed in C, but the first point above demonstrates that return values may not always be what you expect.

Interfaces Without Instance Variables

Omit the empty set of braces on interfaces that do not declare any instance variables.

Cocoa Patterns

Delegate Pattern

Delegates, target objects, and block pointers should not be retained when doing so would create a retain cycle.

To avoid causing a retain cycle, a delegate or target pointer should be released as soon as it is clear there will no longer be a need to message the object.

If there is no clear time at which the delegate or target pointer is no longer needed, the pointer should only be retained weakly.

Block pointers cannot be retained weakly. To avoid causing retain cycles in the client code, block pointers should be used for callbacks only where they can be explicitly released after they have been called or once they are no longer needed. Otherwise, callbacks should be done via weak delegate or target pointers.

Objective-C++

Style Matches the Language

Within an Objective-C++ source file, follow the style for the language of the function or method you’re implementing. In order to minimize clashes between the differing naming styles when mixing Cocoa/Objective-C and C++, follow the style of the method being implemented.

For code in an block, use the Objective-C naming rules. For code in a method of a C++ class, use the C++ naming rules.

For code in an Objective-C++ file outside of a class implementation, be consistent within the file.

Projects may opt to use an 80 column line length limit for consistency with Google’s C++ style guide.

Objective-C Style Exceptions

Indicating style exceptions

Lines of code that are not expected to adhere to these style recommendations require at the end of the line or at the end of the previous line. Sometimes it is required that parts of Objective-C code must ignore these style recommendations (for example code may be machine generated or code constructs are such that its not possible to style correctly).

A comment on that line or on the previous line can be used to indicate to the reader that code is intentionally ignoring style guidelines. In addition these annotations can also be picked up by automated tools such as linters and handle code correctly. Note that there is a single space between and .

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *