Objective-C Cheat Sheet and Quick Reference
Class Header (.h) Creating a Class Instance Declaring Variables
#import "AnyHeaderFile.h" ClassName * myClass = anytype myVariable;
[[ClassName alloc] init];
@interface ClassName : SuperClass { // myClass valid until you call: int 1, 2, 500, 10000
//declare instance variables [myClass release]; // Don’t need w/ ARC float 1.5, 3.14, 578.234
} double
// define properties ClassName * myClass = BOOL YES, NO, TRUE, FALSE
// define methods (including any [[[ClassName alloc] init] ClassName * NSString *, NSArray *, etc.
// custom initializers) autorelease]; id Can hold ref to any object
@end // myClass valid until next run loop
Class Implementation (.m) Calling a Method Custom Initializer Example
- (id)initWithParam:(anytype)param {
#import "YourClassName.h" [myClass doIt]; if ((self = [super init])) {
[myClass doItWithA:a]; self.propertyName = param;
@implementation ClassName [myClass doItWithA:a andB:b]; }
// synthesize properties return self;
// implement methods (including any
// custom initializers, and dealloc) Defining Properties }
@end
@property (attribute1, attribute2) NSString Quick Examples
propertyName;
Defining Methods
NSString *personOne = @"Ray";
retain Call retain on assign NSString *personTwo = @"Shawn";
- (anytype)doIt; assign Normal assign (default) NSString *combinedString =
- (anytype)doItWithA:(anytype)a; copy Make copy on assign [NSString stringWithFormat:
- (anytype)doItWithA:(anytype)a nonatomic Make not threadsafe @"%@: Hello, %@!",
andB:(anytype)b; readwrite Create getter&setter (default) personOne, personTwo];
readonly Create just getter NSLog(@"%@", combinedString);
Implementing Methods
NSString *tipString = @"24.99";
float tipFloat = [tipString floatValue];
- (anytype)doItWithA:(anytype)a
Synthesizing Properties
andB:(anytype)b { @synthesize propertyName; NSArray Quick Examples
// Do something with a and b... @synthesize propertyName =
return retVal; _myInstanceVariable; NSMutableArray *array =
} [NSMutableArray arrayWithObjects:
personOne, personTwo, nil];
Dealloc Using Properties [array addObject:@"Waldo"];
NSLog(@"%d items!", array.count);
[myClass setPropertyName:a]; for (NSString *person in array) {
- (void)dealloc {
myClass.propertyName = a; // alternative NSLog(@"Person: %@", person);
// Release any retained variables...
a = [myClass propertyName]; }
[super dealloc];
a = test.propertyName; // alternative NSString *waldo =
}
[array objectAtIndex:2];
Source:
raywenderlich.com.
Visit
for
more
iOS
resources
and
tutorials!
Copyright
2011
Ray
Wenderlich.
All
rights
reserved.