Objective-C Guide

Post on 27-Apr-2015

406 views 4 download

Transcript of Objective-C Guide

.m.c

.mm

@interface ( )

@interface

- (void)encodeWithCoder:(NSCoder *)coder{ [super encodeWithCoder:coder]; ...}

idid

typedef struct objc_object { Class isa;} *id;

isa

typedef struct objc_class *Class;

isa isa

id

id anObject;

id intint

nil id 0 id nilobjc/objc.h

id

id

isa

isa

isa

[receiver message]

myRectangle display

[myRectangle display];

;

:

[myRectangle setWidth:20.0];

myRectangle

[myRectangle setOrigin:30.0 :50.0]; // This is a bad example of multiple arguments

setOrigin::

setOriginX:y:

[myRectangle setOriginX: 30.0 y: 50.0]; // This is a good example of multiple arguments

def func(a, b, NeatMode=SuperNeat, Thing=DefaultThing): pass

makeGroup:

[receiver makeGroup:group, memberOne, memberTwo, memberThree];

isFilledYES myRectangle NO

BOOL isFilled;isFilled = [myRectangle isFilled];

[myRectangle setPrimaryColor:[otherRect primaryColor]];

.

nilnil

■ nil 0 nil

Person *motherInLaw = [[aPerson spouse] mother];

aPerson nil mother nil nil

■ sizeof(void*)float double long double long long nil 0

nil 0.0

nil

nil

id anObjectMaybeNil = nil;

// this is validif ([anObjectMaybeNil methodThatReturnsADouble] == 0.0){ // implementation continues...}

nilvoid sizeof(void*)

nil nil nil

nilsizeof(void*)

primaryColorotherRect

primaryColor isFilled

display

display id display

copy

copy

.[]

myInstance.value = 10;printf("myInstance value: %d", myInstance.value);

[myInstance setValue:10];printf("myInstance value: %d", [myInstance value]);

.

Graphic *graphic = [[Graphic alloc] init];

NSColor *color = graphic.color;CGFloat xLoc = graphic.xLoc;BOOL hidden = graphic.hidden;int textCharacterLength = graphic.text.length;

if (graphic.textHidden != YES) { graphic.text = @"Hello";}graphic.bounds = NSMakeRect(10.0, 10.0, 20.0, 120.0);

@"Hello" NSString

set :

Graphic *graphic = [[Graphic alloc] init];

NSColor *color = [graphic color];CGFloat xLoc = [graphic xLoc];BOOL hidden = [graphic hidden];int textCharacterLength = [[graphic text] length];

if ([graphic isTextHidden] != YES) { [graphic setText:@"Hello"];}[graphic setBounds:NSMakeRect(10.0, 10.0, 20.0, 120.0)];

set :

NSMutableData

NSMutableData *data = [NSMutableData dataWithLength:1024];data.length += 1024;data.length *= 2;data.length /= 4;

[data setLength:[data length] + 1024];[data setLength:[data length] * 2];[data setLength:[data length] / 4];

id y;x = y.z; // z is an undeclared property

y zz

zz BOOL

readonly

nilnil

// each member of the path is an objectx = person.address.street.name;x = [[[person address] street] name];

// the path contains a C struct// will crash if window is nil or -contentView returns nily = window.contentView.bounds.origin.y;y = [[window contentView] bounds].origin.y;

// an example of using a setter....person.address.street.name = @"Oxford Road";[[[person address] street] setName: @"Oxford Road"];

self self

self.age = 10;

self.age

age = 10;

aVariable = anObject.aProperty;

aProperty aVariableaProperty aVariable

anObject.name = @"New Name";

setName anObject @"New Name"

setName name setName:void

xOrigin = aView.bounds.origin.x;

bounds xOrigin origin.xNSRect bounds

NSInteger i = 10;anObject.integerProperty = anotherObject.floatProperty = ++i;

11 anObject.integerProperty anotherObject.floatPropertysetIntegerProperty:

setFloatProperty:

anObject.retain;

warning: value returned from property not used.

/* method declaration */- (BOOL) setFooIfYouCan: (MyClass *)newFoo;

/* code fragment */anObject.fooIfYouCan = myInstance;

setFooIfYouCan:(void)

flag = aView.lockFocusIfCanDraw;

lockFocusIfCanDraw flagflag

/* property declaration */@property(readonly) NSInteger readonlyProperty;/* method declaration */- (void) setReadonlyProperty: (NSInteger)newValue;

/* code fragment */self.readonlyProperty = 5;

readonly warning: assignmentto readonly property 'readonlyProperty'

readwrite

NSMatrix NSWindow NSDictionary NSFontNSTextNSArray NSWindow

NSObject

Image Text

NSObject

Graphic

Shape

Line CircleRectangle

Square

NSObject

NSObjectNSObject

NSObject

NSObject

NSObject

NSObjectNSObject

NSObjectNSObject

NSObject NSObject

isa NSObjectisa

ClassNSPointNSColorPattern. . .floatfloatBOOLNSColor. . .

declared in Shape

declared in Rectangle

declared in NSObjectdeclared in Graphic

isa;origin;*primaryColor;linePattern;

width;height;filled;*fillColor;

NSObject

displaydisplay

display

NSObjectNSObject

NSView

sizeof

int i = sizeof(Rectangle);

id

Rectangle *myRectangle;

idid

id

Graphic *myRectangle;

myRectangle

isMemberOfClass: NSObject

if ( [anObject isMemberOfClass:someClass] ) ...

isKindOfClass: NSObject

if ( [anObject isKindOfClass:someClass] ) ...

isKindOfClass: YES

NSObject isKindOfClass:isMemberOfClass:

NSObject

int versionNumber = [Rectangle version];

id class

id aClass = [anObject class];

id rectClass = [Rectangle class];

id

Class aClass = [anObject class];Class rectClass = [Rectangle class];

myRectangle

id myRectangle;myRectangle = [Rectangle alloc];

alloc0 isa

init

myRectangle = [[Rectangle alloc] init];

myRectanglealloc

initalloc init

initWithPosition:size:

NSMatrixNSCell

NSMatrix

NSMatrix

NSCell

NSCell

NSObject

NSCell

NSActionCell

NSTextFieldCell NSSliderCellNSButtonCell NSFormCell

NSMenuCell

NSBrowserCell

NSCell NSButtonCellNSTextFieldCellNSCell NSMatrix

NSMatrix

NSMatrixNSMatrix

NSCell NSMatrixNSCell NSMatrix

NSMatrix

NSMatrix NSMatrixNSCell setCellClass:NSCell NSMatrix

[myMatrix setCellClass:[NSButtonCell class]];

NSMatrix

int MCLSGlobalVariable;

@implementation MyClass// implementation continues

staticstatic

static MyClass *MCLSSharedInstance;

@implementation MyClass

+ (MyClass *)sharedInstance{ // check for existence of shared instance // create if necessary return MCLSSharedInstance;}// implementation continues

static

initializeinitialize

initializeinitialize

initialize

initialize initializeinitialize

initializeinitialize

initialize initializeinitialize

initialize

+ (void)initialize{ if (self == [ThisClass class]) { // Perform initialization here. ... }}

initializeinitialize initialize

NSObject

NSObject

NSObject

Rectangle *anObject;

anObject

id classisKindOfClass:

if ( [anObject isKindOfClass:[Rectangle class]] ) ...

NSClassFromString

NSString *className; ...if ( [anObject isKindOfClass:NSClassFromString(className)] ) ...

nil

classclass

[object class] != object_getClass(object) != *((Class*)object)

if ([objectA class] == [objectB class]) { //...

.m

.h Rectangle.hRectangle.m

@interface@end

@interface ClassName : ItsSuperclass{ instance variable declarations}method declarations@end

NSObject

float width;float height;BOOL filled;NSColor *fillColor;

+ alloc;

- (void)display;

radiusradius

- (float)radius;

- (void)setRadius:(float)aRadius;

id alloc id

- (void)setWidth:(float)width height:(float)height;

- makeGroup:group, ...;

#import

#import "Rectangle.h"

#include#include

#import "ItsSuperclass.h"

@interface ClassName : ItsSuperclass{ instance variable declarations}method declarations@end

NSObject@class

@class Rectangle, Circle;

- (void)setPrimaryColor:(NSColor *)aColor;

NSColor

@class

@class

@class

@implementation@end

@implementation ClassName : ItsSuperclass{ instance variable declarations}method definitions@end

Rectangle.mRectangle.h

#import "ClassName.h"

@implementation ClassNamemethod definitions@end

+ (id)alloc{ ...}

- (BOOL)isFilled{ ...}

- (void)setFilled:(BOOL)flag{ ...}

#import <stdarg.h>

...

- getGroup:group, ...{ va_list ap; va_start(ap, group); ...}

. ->filled

- (void)setFilled:(BOOL)flag{ filled = flag; ...}

filled

->

twin

@interface Sibling : NSObject{ Sibling *twin; int gender; struct features *appearance;}

twin

- makeIdenticalTwin{ if ( !twin ) { twin = [[Sibling alloc] init]; twin->gender = gender; twin->appearance = appearance; } return twin;}

- (BOOL)isFilled{ return filled;}

@private

@protected

@public

@package @public@private

private_extern

@private@protected @public

@package

Unrelated code

The class that declares the

instance variable

A class thatinherits the

instance variable

@private

@protected

@public

age evaluation name job wageboss

@interface Worker : NSObject{ char *name;@private int age; char *evaluation;@protected id job; float wage;

@public id boss;}

name @protected

job

- promoteTo:newPosition{ id old = job; job = newPosition; return old;}

promoteTo:job

@private@private

@public

Worker *ceo = [[Worker alloc] init];ceo->boss = nil;

@public

self super

repositionsetOrigin::

setOrigin:: repositionself super reposition

- reposition{ ... [self setOrigin:someX :someY]; ...}

- reposition{ ... [super setOrigin:someX :someY]; ...}

self super repositionself

super self

■ self

■ supersuper

superobjc_msgSend

super

self super

negotiatemakeLastingPeace negotiate

Mid

High

Low

superclass

– negotiate

superclass

– negotiate

superclass

– negotiate

– makeLastingPeace

makeLastingPeacemakeLastingPeace negotiate

self

- makeLastingPeace{ [self negotiate]; ...}

negotiate selfsuper

- makeLastingPeace{ [super negotiate]; ...}

negotiatemakeLastingPeace

negotiate

supermakeLastingPeace negotiate

negotiate

■ negotiate

■ super makeLastingPeacenegotiate

negotiate

negotiate

super

- negotiate{ ... return [super negotiate];}

super initinit

init superinit

- (id)init{ if (self = [super init]) { ... }}

superisa

alloc allocWithZone: NSObjectsuper

superself

selfself super

selfself

+ (Rectangle *)rectangleOfColor:(NSColor *) color{ self = [[Rectangle alloc] init]; // BAD [self setColor:color]; return [self autorelease];}

self

+ (id)rectangleOfColor:(NSColor *)color{ id newInstance = [[Rectangle alloc] init]; // GOOD [newInstance setColor:color]; return [newInstance autorelease];}

alloc allocself rectangleOfColor:

array NSArrayNSMutableArray

+ (id)rectangleOfColor:(NSColor *)color{ id newInstance = [[self alloc] init]; // EXCELLENT [newInstance setColor:color]; return [newInstance autorelease];}

id anObject = [[Rectangle alloc] init];

NSObjectNSObject alloc allocWithZone:

alloc allocWithZone: isa0

initNSView

initWithFrame:

init... NSObjectisa init isa

NSObject init self NSObject

init...

initWithName:initWithName:

init...initFromFile:

init... nil

init...nil

alloc allocWithZone: init

id anObject = [SomeClass alloc];[anObject init];[anObject someOtherMessage];

id anObject = [[SomeClass alloc] init];[anObject someOtherMessage];

init... nil

id anObject = [[SomeClass alloc] init];if ( anObject ) [anObject someOtherMessage];else ...

isa0

■ init

initWithFormat: initWithObjects:initWithObjectsAndKeys:

■ id

idNSString

initWithFormat: NSMutableStringNSString NSMutableString NSString

NSObject init

■ self

■ selfnil

NSObject creationDate

- (id)init { // Assign self to value returned by super's designated initializer // Designated initializer for NSObject is init if (self = [super init]) { creationDate = [[NSDate alloc] init]; } return self;}

if (self = [super init])

initWithName:fromURL:

setEnabled: setFriend: setDimensions:

NSView

- (id)initWithImage:(NSImage *)anImage {

// Find the size for the new instance from the image NSSize size = anImage.size; NSRect frame = NSMakeRect(0.0, 0.0, size.width, size.height);

// Assign self to value returned by super's designated initializer // Designated initializer for NSView is initWithFrame: if (self = [super initWithFrame:frame]) {

image = [anImage retain]; } return self;}

[self release]nil

■ nil

■ dealloc

[self release] nilrelease

dealloc nil

- (id)init { if (self = [super init]) { creationDate = [[NSDate alloc] init]; } return self;}

- (id)initWithImage:(NSImage *)anImage {

if (anImage == nil) { [self release]; return nil; }

// Find the size for the new instance from the image NSSize size = anImage.size; NSRect frame = NSMakeRect(0.0, 0.0, size.width, size.height);

// Assign self to value returned by super's designated initializer // Designated initializer for NSView is initWithFrame: if (self = [super initWithFrame:frame]) {

image = [anImage retain]; } return self;}

NSError

- (id)initWithURL:(NSURL *)aURL error:(NSError **)errorPtr {

if (self = [super init]) {

NSData *data = [[NSData alloc] initWithContentsOfURL:aURL options:NSUncachedRead error:errorPtr];

if (data == nil) { // In this case the error object is created in the NSData initializer [self release]; return nil; } // implementation continues...

init...super

- (id)initWithName:(NSString *)string { if ( self = [super init] ) { name = [string copy]; } return self;}

super

NSObject

initWithName: init

Class B

Class A

– init

– initWithName:

init initWithName:init

init initWithName:

- init { return [self initWithName:"default"];}

initWithName:init

Class B

Class A

– init

– init

– initWithName:

initWithName:

super

initWithName:fromFile:init initWithName:

initWithName: initWithName:fromFile:

- initWithName:(char *)string { return [self initWithName:string fromFile:NULL];}

init initWithName:initWithName:fromFile:

– initWithName:fromFile:

– initWithName:

Class B

– init

Class C

– initWithName:

initWithName:fromFile:super

init initWithName: init

■ init initWithName: initWithName:fromFile:init

■ initWithName:

initWithName:fromFile: initWithName:

- initWithName:(char *)string fromFile:(char *)pathname { if ( self = [super initWithName:string] ) ...}

super

superself

selfsuper

– initWithName:fromFile:

– initWithName:

Class B

Class A

– init

– init

Class C

– initWithName:

init self initWithName:initWithName:

+ NSString

+ (id)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc;+ (id)stringWithFormat:(NSString *)format, ...;

NSArray

+ (id)array;

+ (id)arrayWithObject:(id)anObject;+ (id)arrayWithObjects:(id)firstObj, ...;

id

listFromFile:

init...initWithName:

init...

soloist

+ (Soloist *)soloist { static Soloist *instance = nil;

if ( instance == nil ) { instance = [[self alloc] init]; } return instance;}

Soloist *

- (void)mouseDown:(NSEvent *)theEvent;- (void)mouseDragged:(NSEvent *)theEvent;- (void)mouseUp:(NSEvent *)theEvent;

helpOut: assistant

- setAssistant:anObject{ assistant = anObject;}

assistant

- (BOOL)doWork{ ... if ( [assistant respondsToSelector:@selector(helpOut:)] ) { [assistant helpOut:self]; return YES; } return NO;}

assistant helpOut:

id formatter = [receiver formattingService];

- (NSXMLElement *)XMLRepresentation;- initFromXMLRepresentation:(NSXMLElement *)xmlString;

NSMatrixNSCell

NSCell NSMatrixNSMatrix

NSMatrix

@protocol

@protocol ProtocolNamemethod declarations@end

@protocol MyXMLSupport- initFromXMLRepresentation:(NSXMLElement *)XMLElement;- (NSXMLElement *)XMLRepresentation;@end

@optional @optional@required

@optional @required@required

@protocol MyProtocol

- (void)requiredMethod;

@optional- (void)anOptionalMethod;- (void)anotherOptionalMethod;

@required- (void)anotherRequiredMethod;

@end

@interface NSObject ( MyXMLSupport )- initFromXMLRepresentation:(NSXMLElement *)XMLElement;- (NSXMLElement *)XMLRepresentation;@end

NSObjectNSObject

@protocol()

Protocol *myXMLSupportProtocol = @protocol(MyXMLSupport);

@protocol()

■ @protocol()

@interface ClassName : ItsSuperclass < protocol list >

@interface ClassName ( CategoryName ) < protocol list >

@interface Formatter : NSObject < Formatting, Prettifying >

@interface Formatter : NSObject < Formatting, Prettifying >@end

conformsToProtocol:

if ( ! [receiver conformsToProtocol:@protocol(MyXMLSupport)] ) { // Object does not conform to MyXMLSupport protocol // If you are expecting receiver to implement methods declared in the // MyXMLSupport protocol, this is probably an error}

conformsToProtocol:

conformsToProtocol: respondsToSelector:

conformsToProtocol: respondsToSelector:

conformsToProtocol: isKindOfClass:

- (id <Formatting>)formattingService;id <MyXMLSupport> anObject;

Formatter *anObject;

id <Formatting> anObject;

Formatter <Formatting> *anObject;

conformsToProtocol:

@protocol ProtocolName < protocol list >

@protocol Paging < Formatting >

id <Paging> someObject;

conformsToProtocol:

if ( [anotherObject conformsToProtocol:@protocol(Paging)] ) ...

NSObject

@interface Pager : NSObject < Paging >

@interface Pager : Formatter < Paging >

#import "B.h"

@protocol A- foo:(id <B>)anObject;@end

#import "A.h"

@protocol B- bar:(id <A>)anObject;@end

@protocol

@protocol B;

@protocol A- foo:(id <B>)anObject;@end

@protocol

@property @property@interface @property

@property(attributes) type name;@property

@interface MyClass : NSObject{ float value;}@property float value;@end

@property float value;

- (float)value;- (void)setValue:(float)newValue;

@property(attribute [, attribute2,...])

@synthesize

copy

set : foosetFoo:

readonly setter=

getter=getterName

setter=setterName

void

readonly setter=

getteris

readwrite

@implementation @synthesize

readonly

readonly @implementation@synthesize

assign

NSInteger CGRect

retain assign

retainretain assign

release

retain

@property(retain) __attribute__((NSObject)) CFDictionaryRef myDictionary;

copyassign

release

copyNSCopying

■ assignretain copy

assign retain copy NSCopying

nonatomic

nonatomic

[_internal lock]; // lock using an object-level lockid result = [[value retain] autorelease];[_internal unlock];return result;

nonatomic

__attribute__

@property CGFloat xAVAILABLE_MAC_OS_X_VERSION_10_1_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_4;@property CGFloat y __attribute__((...));

IBOutlet

@property (nonatomic, retain) IBOutlet NSButton *myButton;

IBOutlet

__weak __strong

@property (nonatomic, retain) __weak Link *parent;

@synthesize @dynamic @implementation@property

@synthesize @dynamicreadonly

@synthesize@synthesize

@implementation

@interface MyClass : NSObject{ NSString *value;}@property(copy, readwrite) NSString *value;@end

@implementation MyClass@synthesize value;@end

property=ivar

@synthesize firstName, lastName, age = yearsOld;

firstName lastName ageage yearsOld

@synthesize

■ @interface

@dynamic@dynamic

@interface MyClass : NSObject{ NSString *value;}@property(copy, readwrite) NSString *value;@end

// assume using garbage collection@implementation MyClass@dynamic value;

- (NSString *)value { return value;}

- (void)setValue:(NSString *)newValue { if (newValue != value) { value = [newValue copy]; }}@end

readonly readwrite

readonly readwrite

@synthesize

NSStringNSArray NSDictionary readonly

readwrite

// public header file@interface MyObject : NSObject { NSString *language;}@property (readonly, copy) NSString *language;@end

// private implementation file@interface MyObject ()@property (readwrite, copy) NSString *language;@end

@implementation MyObject@synthesize language;@end

copycopy

NSMutableString

@property (nonatomic, copy) NSString *string;

-(void)setString:(NSString *)newString { if (string != newString) { [string release]; string = [newString copy]; }}

copy

@interface MyClass : NSObject { NSMutableArray *myArray;}@property (nonatomic, copy) NSMutableArray *myArray;@end

@implementation MyClass

@synthesize myArray;

- (void)setMyArray:(NSMutableArray *)newArray { if (myArray != newArray) { [myArray release]; myArray = [newArray mutableCopy]; }}

@end

deallocdealloc

assignassign

deallocnil

- (void)dealloc { [property release]; [super dealloc];}

- (void)dealloc { [self setProperty:nil]; [super dealloc];}

retain

@interface MyClass : NSObject{ CGImageRef myImage;}@property(readwrite) CGImageRef myImage;@end

@implementation MyClass@synthesize myImage;@end

__strong

...__strong CGImageRef myImage;...@property CGImageRef myImage;

■ next

■ next

■ creationTimestamp next

■ name

■ gratuitousFloat dynamic

■ nameAndAge dynamic

nameAndAgeAsString

@protocol Link@property id <Link> next;@end

@interface MyClass : NSObject <Link>{ NSTimeInterval intervalSinceReferenceDate; CGFloat gratuitousFloat; id <Link> nextLink;}@property(readonly) NSTimeInterval creationTimestamp;@property(copy) NSString *name;@property CGFloat gratuitousFloat;@property(readonly, getter=nameAndAgeAsString) NSString *nameAndAge;

@end

@implementation MyClass

@synthesize creationTimestamp = intervalSinceReferenceDate, name;// Synthesizing 'name' is an error in legacy runtimes;// in modern runtimes, the instance variable is synthesized.

@synthesize next = nextLink;// Uses instance variable "nextLink" for storage.

@dynamic gratuitousFloat;// This directive is not strictly necessary.

- (CGFloat)gratuitousFloat { return gratuitousFloat;}- (void)setGratuitousFloat:(CGFloat)aValue { gratuitousFloat = aValue;}

- (NSString *)nameAndAgeAsString { return [NSString stringWithFormat:@"%@ (%fs)", [self name], [NSDate timeIntervalSinceReferenceDate] - intervalSinceReferenceDate];}

- (id)init { if (self = [super init]) { intervalSinceReferenceDate = [NSDate timeIntervalSinceReferenceDate]; } return self;}

- (void)dealloc { [nextLink release]; [name release]; [super dealloc];}

@end

readonly MyIntegerreadonly value

@interface MyInteger : NSObject{ NSInteger value;}@property(readonly) NSInteger value;@end

@implementation MyInteger

@synthesize value;@end

MyMutableInteger

@interface MyMutableInteger : MyInteger@property(readwrite) NSInteger value;@end

@implementation MyMutableInteger@dynamic value;

- (void)setValue:(NSInteger)newX { value = newX;}@end

retainassign copy nonatomic

// assignproperty = newValue;

// retainif (property != newValue) { [property release]; property = [newValue retain];}

// copyif (property != newValue) { [property release]; property = [newValue copy];}

nonatomic

@synthesize@synthesize

@interface MyClass : NSObject { float sameName; float otherName;}@property float sameName;@property float differentName;@property float noDeclaredIvar;@end

@implementation MyClass@synthesize sameName;@synthesize differentName=otherName;@synthesize noDeclaredIvar;@end

@synthesize noDeclaredIvar;noDeclaredIvar

@interface

NSArrayNSArray

NSArray NSArray

#import "ClassName.h"

@interface ClassName ( CategoryName )// method declarations@end

ClassName+CategoryName.m

#import "ClassName+CategoryName.h"

@implementation ClassName ( CategoryName )// method definitions@end

@private

NSArray

super

windowWillClose: NSObjectNSWindow

NSObject

■ super

NSObjectself

NSObject

@implementation

@interface MyObject : NSObject{

NSNumber *number;}- (NSNumber *)number;@end

@interface MyObject (Setter)- (void)setNumber:(NSNumber *)newNumber;@end

@implementation MyObject

- (NSNumber *)number { return number;}@end

setNumber:

@interface

@interface MyObject : NSObject{ NSNumber *number;}- (NSNumber *)number;@end

@interface MyObject ()- (void)setNumber:(NSNumber *)newNumber;@end

@implementation MyObject

- (NSNumber *)number { return number;}- (void)setNumber:(NSNumber *)newNumber { number = newNumber;}@end

■ @interface

■ setNumber: @implementation

setNumber: @implementation

setNumber:

objc_setAssociatedObject

■ voidstatic

objc_AssociationPolicy

static char overviewKey;

NSArray *array = [[NSArray alloc] initWithObjects:@"One", @"Two", @"Three", nil];// For the purposes of illustration, use initWithFormat: to ensure the string can be deallocatedNSString *overview = [[NSString alloc] initWithFormat:@"%@", @"First three numbers"];

objc_setAssociatedObject(array, &overviewKey, overview, OBJC_ASSOCIATION_RETAIN);

[overview release];// (1) overview valid[array release];// (2) overview invalid

overview OBJC_ASSOCIATION_RETAINoverview

overview

objc_getAssociatedObject

NSString *associatedObject = (NSString *)objc_getAssociatedObject(array, &overviewKey);

objc_setAssociatedObject nil

overview

objc_setAssociatedObject(array, &overviewKey, nil, OBJC_ASSOCIATION_ASSIGN);

nil

objc_removeAssociatedObjects

#import <Foundation/Foundation.h>#import <objc/runtime.h>

int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

static char overviewKey;

NSArray *array = [[NSArray alloc] initWithObjects:@"One", @"Two", @"Three", nil]; // For the purposes of illustration, use initWithFormat: to ensure we get a // deallocatable string NSString *overview = [[NSString alloc] initWithFormat:@"%@", @"First three numbers"];

objc_setAssociatedObject(array, &overviewKey, overview, OBJC_ASSOCIATION_RETAIN); [overview release];

NSString *associatedObject = (NSString *)objc_getAssociatedObject(array, &overviewKey); NSLog(@"associatedObject: %@", associatedObject");

objc_setAssociatedObject(array, &overviewKey, nil, OBJC_ASSOCIATION_ASSIGN); [array release];

[pool drain]; return 0;}

for ( Type newVariable in expression ) { statements }

Type existingItem;for ( existingItem in expression ) { statements }

NSFastEnumeration

statements nil

■ NSEnumerator

NSFastEnumerationNSArray NSDictionary NSSet

NSEnumerator NSArray NSSet

NSDictionary NSManagedObjectModelNSDictionary NSManagedObjectModel

NSArray NSDictionary

NSArray *array = [NSArray arrayWithObjects: @"One", @"Two", @"Three", @"Four", nil];

for (NSString *element in array) { NSLog(@"element: %@", element);}

NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys: @"quattuor", @"four", @"quinque", @"five", @"sex", @"six", nil];

NSString *key;for (key in dictionary) { NSLog(@"English: %@, Latin: %@", key, [dictionary valueForKey:key]);}

NSEnumerator

NSArray *array = [NSArray arrayWithObjects: @"One", @"Two", @"Three", @"Four", nil];

NSEnumerator *enumerator = [array reverseObjectEnumerator];for (NSString *element in enumerator) { if ([element isEqualToString:@"Three"]) { break; }}

NSString *next = [enumerator nextObject];// next = "Two"

NSArray NSEnumerator

NSArray *array = /* assume this exists */;NSUInteger index = 0;

for (id element in array) { NSLog(@"Element at index %u is: %@", index, element); index++;}

for break

NSArray *array = /* assume this exists */;

for (id element in array) { if (/* some test for element */) { // statements that apply only to elements passing test }

}

NSArray *array = /* assume this exists */;NSUInteger index = 0;

for (id element in array) { if (index != 0) { NSLog(@"Element at index %u is: %@", index, element); }

if (++index >= 6) { break; }}

■ idid

id

id

id

Rectangle *thisObject;

thisObject

id

id

Rectangle *thisObject = [[Square alloc] init];

iddisplay

thisObject

[thisObject display];

id

Shape *aShape;Rectangle *aRect;

aRect = [[Rectangle alloc] init];aShape = aRect;

aRect aShapeaShape aRect

idid id alloc

init id

Rectangle *aRect;aRect = [[Shape alloc] init];

NSObject

Shape *myRectangle = [[Rectangle alloc] init];

BOOL solid = [myRectangle isFilled];

isFilled

[myRectangle display];

worry double

- (double)worry;

- (int)worry;

worrydouble worry int

worry double int

SEL

SEL0 SEL

@selector()setWidth:height: setWidthHeight

SEL setWidthHeight;setWidthHeight = @selector(setWidth:height:);

SEL @selector()

NSSelectorFromString

setWidthHeight = NSSelectorFromString(aBuffer);

NSStringFromSelector

NSString *method;method = NSStringFromSelector(setWidthHeight);

displaydisplay

displaydisplay

performSelector: performSelector:withObject:performSelector:withObject:withObject: NSObject SEL

[friend performSelector:@selector(gossipAbout:) withObject:aNeighbor];

[friend gossipAbout:aNeighbor];

id helper = getTheReceiver();SEL request = getTheSelector();[helper performSelector:request];

helper getTheReceiverrequest

getTheSelector

performSelector: id

NSControl

NSButtonCell NSMatrix

NSButtonCellNSButtonCell

NSButtonCell

[myButtonCell setAction:@selector(reapTheWind:)];[myButtonCell setTarget:anObject];

NSObject performSelector:withObject:id

NSButtonCellNSButtonCell

respondsToSelector: NSObject

if ( [anObject respondsToSelector:@selector(setOrigin::)] ) [anObject setOrigin:0.0 :0.0];else fprintf(stderr, "%s can’t be placed\n", [NSStringFromClass([anObject class]) UTF8String]);

respondsToSelector:

NSException NSError

-fobjc-exceptions

@try @catch @throw@finally

■ @try

■ @catch() @try@catch()

■ @finally

■ @throwNSException

Cup *cup = [[Cup alloc] init];

@try { [cup fill];}

@catch (NSException *exception) { NSLog(@"main: Caught %@: %@", [exception name], [exception reason]);}@finally { [cup release];}

@try @catch() @try@catch()

@try { ...}@catch (CustomException *ce) { // 1 ...}@catch (NSException *ne) { // 2 // Perform processing necessary at this level. ...

}@catch (id ue) { ...}@finally { // 3 // Perform processing necessary whether an exception occurred or not. ...}

NSException *exception = [NSException exceptionWithName:@"HotTeaException" reason:@"The tea is too hot" userInfo:nil];

@throw exception;

@catch() @throw

NSExceptionNSException

NSException

-fobjc-exceptions

@synchronized()

@synchronized()

@synchronized()

@synchronized() self

self

self

- (void)criticalMethod{ @synchronized(self) { // Critical code. ... }}

initialize

Account *account = [Account accountFromString:[accountField stringValue]];

// Get the semaphore.id accountSemaphore = [Account semaphore];

@synchronized(accountSemaphore) { // Critical code. ...}

@synchronized()

@synchronized()

BAProxy

forB

conformsToProtocol: @protocol()

NSProxy NSConnection

onewayinoutinoutbycopy

byref

- (BOOL)canDance;

canDance

initial message

return information

AProxy

forB

B

oneway

- (oneway void)waltzAtWill;

oneway constoneway float oneway id oneway void

- setTune:(struct tune *)aSong{ tune = *aSong; ...}

- getTune:(struct tune *)theSong{ ... *theSong = tune;}

■ in

- setTune:(in struct tune *)aSong;

■ out

- getTune:(out struct tune *)theSong;

■ inout

- adjustTune:(inout struct tune *)aSong;

inoutconst in inout

in in outinout

char *

out inout

- getTuneTitle:(out char **)theTitle;

- adjustRectangle:(inout Rectangle **)theRect;

- danceWith:(id)aPartner;

danceWith: idaPartner

danceWith:

bycopy

- danceWith:(bycopy id)aClone;

bycopy

- (bycopy)dancer;

out

- getDancer:(bycopy out id *)theDancer;

bycopy

byref

byref

bycopy byrefid

bycopy byreffoo

@Protocol foo- (bycopy)array;@end

foo

/* Hello.mm * Compile with: g++ -x objective-c++ -framework Foundation Hello.mm -o hello */

#import <Foundation/Foundation.h>class Hello { private: id greeting_text; // holds an NSString public: Hello() { greeting_text = @"Hello, world!"; } Hello(const char* initial_greeting_text) { greeting_text = [[NSString alloc] initWithUTF8String:initial_greeting_text]; } void say_hello() { printf("%s\n", [greeting_text UTF8String]); }};

@interface Greeting : NSObject { @private Hello *hello;}- (id)init;- (void)dealloc;- (void)sayGreeting;- (void)sayGreeting:(Hello*)greeting;

@end

@implementation Greeting- (id)init { if (self = [super init]) { hello = new Hello(); } return self;}- (void)dealloc { delete hello; [super dealloc];}- (void)sayGreeting { hello->say_hello();}- (void)sayGreeting:(Hello*)greeting { greeting->say_hello();}@end

int main() { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

Greeting *greeting = [[Greeting alloc] init]; [greeting sayGreeting]; // > Hello, world!

Hello *hello = new Hello("Bonjour, monde!"); [greeting sayGreeting:hello]; // > Bonjour, monde!

delete hello; [greeting release]; [pool release]; return 0;}

__cplusplus __OBJC__

class Base { /* ... */ };@interface ObjCClass: Base ... @end // ERROR!class Derived: public ObjCClass ... // ERROR!

@interface Foo { class Bar { ... } // OK}@end

Bar *barPtr; // OK

@interface Foo { struct CStruct { ... }; struct CStruct bigIvar; // OK} ... @end

fobjc-call-cxx-cdtors

fobjc-call-cxx-cdtorsalloc class_createInstance

deallocobject_dispose

#import <Cocoa/Cocoa.h>

struct Class0 { void foo(); };struct Class1 { virtual void foo(); };struct Class2 { Class2(int i, int j); };

@interface Foo : NSObject { Class0 class0; // OK Class1 class1; // ERROR! Class1 *ptr; // OK—call 'ptr = new Class1()' from Foo's init, // 'delete ptr' from Foo's dealloc Class2 class2; // WARNING - constructor not called!...@end

id Class SEL IMP BOOL

self superthis this self super

onewayin out inout bycopy

classNSObject class

[foo class]; // OK

class

NSObject *class; // Error

@interfacefoo @interface(foo)

id<someProtocolName> foo;TemplateType<SomeTypeName> bar;

id

label: ::global_name = 3;

receiver selector: ::global_c++_name;

this self

[receiver message]

■ self

■ super

objc/objc.h

id

Class

SEL

idIMP

YES NO

BOOL char

BOOL

id

objc.h

(id)0nil

(Class)0Nil

(BOOL)0NO

(BOOL)1YES

#include#import

//

@interface

@implementation

@protocol

@end

@private

@protected

@public

@protected

@try

@throw

@try@catch()

@try@finally

@property

@synthesize

@dynamic

@class

@selector(method_name)

@protocol@protocol(protocol_name)

@encode(type_spec)

NSString@"string"

NSString@"string1" @"string2" ...@"stringN"

@synchronized()

@interface

#import "ItsSuperclass.h"

@interface ClassName : ItsSuperclass < protocol_list >{ instance variable declarations}method declarations@end

#import "ClassName.h"

@implementation ClassNamemethod definitions@end

#import "ClassName.h"

@interface ClassName ( CategoryName ) < protocol list >method declarations@end

#import "CategoryName.h"

@implementation ClassName ( CategoryName )method definitions@end

@protocol

@protocol ProtocolName < protocol list >declarations of required methods@optionaldeclarations of optional methods@requireddeclarations of required methods@end

@optional @required

@required

@protocol

@protocol ProtocolName;

@protocol()

oneway

in

out

inout

bycopy

byref

- (void)setWidth:(int)newWidth height:(int)newHeight

- (void)setWidthAndHeight:(int)newWidth :(int)newHeight

■ id intunsigned unsigned int

■ self

■ _cmd

self super super self

void

@interface SomeClass-method __attribute__((deprecated));

@end

#include <AvailabilityMacros.h>@interface SomeClass-method DEPRECATED_ATTRIBUTE; // or some other deployment-target-specific macro@end

.m.h

initialize

conformsTo: conformsToProtocol:

id

Ivar objc_ivar_list

class_getInstanceMethodclass_getClassMethod

method_getArgumentInfo

NSData

NSView

init...

selfinit...

super

@protocol

id

NSObject

NSObject

NSApplication

id

SEL

//@""

_cmd__cplusplus__OBJC__

alloc

allocWithZone:

BOOLbycopybyref

.c

@catch()

Class@class

self

//

conformsToProtocol:

@encode()@end

@finally

.h

id

IMP@implementation

#importin#include#include #import

initinitialize

inout

@interface

isaisKindOfClass:isMemberOfClass:

.m

super

.mm

NilnilNONSClassFromString

NSSelectorFromStringNSStringFromSelector

onewayout

performSelector:performSelector:withObject:performSelector:withObject:withObject:

@private

@protected@protocol

@public

respondsToSelector:

SEL@selector()

self

super

@synchronized()

this@throw@try

unsigned int

void

YES