<<

Objective-C Cheat Sheet and Quick Reference Class Header (.h) Creating an Object What is a Property?

#import "AnyHeaderFile.h" ClassName * myObject = 1) Automatically defines a private instance variable: [[ClassName alloc] init]; type _propertyName; @interface ClassName : SuperClass 2) Automatically creates a getter and setter: // define public properties Calling a Method // define public methods - (type)propertyName; [myObject doIt]; - (void)setPropertyName:(type)name; [myObject doItWithA:a]; @end Using _propertyName uses the private instance [myObject doItWithA:a b:b]; variable directly. Using self.propertyName uses

Class Implementation (.m) the getter/setter. Declaring Variables #import "YourClassName.h" Custom Initializer Example type myVariable;

@interface ClassName () - (id)initWithParam:(type)param { // define private properties Variable types if ((self = [super init])) { // define private methods int 1, 2, 500, 10000 _propertyName = param; @end float 1.5, 3.14, 578.234 } double return self; @implementation ClassName { BOOL YES, NO } // define private instance variables ClassName * NSString *, NSArray *, etc. } id Can hold reference to any object NSString Quick Examples // implement methods Defining Properties NSString *personOne = @"Ray"; @end NSString *personTwo = @"Shawn"; @property (attribute1, attribute2) NSString *combinedString = type propertyName; [NSString stringWithFormat: Defining Methods @"%@: Hello, %@!", strong Adds reference to keep object alive personOne, personTwo]; - (type)doIt; weak Object can disappear, become nil NSLog(@"%@", combinedString); - (type)doItWithA:(type)a; assign Normal assign, no reference NSString *tipString = @"24.99"; - (type)doItWithA:(type)a copy Make copy on assign float tipFloat = [tipString floatValue]; b:(type)b; nonatomic Make not threadsafe, increase perf

readwrite Create getter&setter (default) NSArray Quick Examples readonly Create just getter Implementing Methods NSMutableArray *array = - (type)doItWithA:(type)a Using Properties [@[person1, person2] mutableCopy]; b:(type)b { [array addObject:@"Waldo"]; // Do something with a and b... [myObject setPropertyName:a]; NSLog(@"% items!", [array count]); return retVal; for (NSString *person in array) { } myObject.propertyName = a; // alt NSLog(@"Person: %@", person); a = [myObject propertyName]; } NSString *waldo = array[2]; a = myObject.propertyName; // alt Source: raywenderlich.com. Visit for more iOS resources and tutorials! Version 1.5. Copyright 2013 Ray Wenderlich. All rights reserved.