Objective-C Guide

137
6JG 1DLGEVKXG% 2TQITCOOKPI .CPIWCIG .CPIWCIGU

Transcript of Objective-C Guide

Page 1: Objective-C Guide
Page 2: Objective-C Guide
Page 3: Objective-C Guide
Page 4: Objective-C Guide
Page 5: Objective-C Guide
Page 6: Objective-C Guide
Page 7: Objective-C Guide
Page 8: Objective-C Guide
Page 9: Objective-C Guide

Page 10: Objective-C Guide

.m.c

.mm

@interface ( )

@interface

Page 11: Objective-C Guide

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

Page 12: Objective-C Guide
Page 13: Objective-C Guide
Page 14: Objective-C Guide

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

Page 15: Objective-C Guide

isa

isa

isa

Page 16: Objective-C Guide

[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

Page 17: Objective-C Guide

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

Page 18: Objective-C Guide

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

Page 19: Objective-C Guide

display

display id display

copy

copy

Page 20: Objective-C Guide

.[]

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

Page 21: Objective-C Guide

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

Page 22: Objective-C Guide

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

Page 23: Objective-C Guide

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

Page 24: Objective-C Guide

NSObject

Image Text

NSObject

Graphic

Shape

Line CircleRectangle

Square

NSObject

NSObjectNSObject

NSObject

Page 25: Objective-C Guide

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;

Page 26: Objective-C Guide

NSObject

displaydisplay

display

Page 27: Objective-C Guide

NSObjectNSObject

NSView

sizeof

int i = sizeof(Rectangle);

id

Rectangle *myRectangle;

idid

id

Graphic *myRectangle;

myRectangle

Page 28: Objective-C Guide

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];

Page 29: Objective-C Guide

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

Page 30: Objective-C Guide

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

Page 31: Objective-C Guide

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

Page 32: Objective-C Guide

initializeinitialize

initialize

initialize initializeinitialize

initializeinitialize

initialize initializeinitialize

initialize

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

initializeinitialize initialize

NSObject

NSObject

NSObject

Page 33: Objective-C Guide

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]) { //...

Page 34: Objective-C Guide
Page 35: Objective-C Guide

.m

.h Rectangle.hRectangle.m

@interface@end

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

Page 36: Objective-C Guide

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, ...;

Page 37: Objective-C Guide

#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

Page 38: Objective-C Guide

@class

@class

@implementation@end

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

Rectangle.mRectangle.h

Page 39: Objective-C Guide

#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

Page 40: Objective-C Guide

->

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

Page 41: Objective-C Guide

@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;

Page 42: Objective-C Guide

@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

Page 43: Objective-C Guide

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

Page 44: Objective-C Guide

self super

negotiatemakeLastingPeace negotiate

Mid

High

Low

superclass

– negotiate

superclass

– negotiate

superclass

– negotiate

– makeLastingPeace

makeLastingPeacemakeLastingPeace negotiate

self

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

negotiate selfsuper

Page 45: Objective-C Guide

- 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]) { ... }}

Page 46: Objective-C Guide

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];}

Page 47: Objective-C Guide

id anObject = [[Rectangle alloc] init];

NSObjectNSObject alloc allocWithZone:

alloc allocWithZone: isa0

initNSView

initWithFrame:

init... NSObjectisa init isa

NSObject init self NSObject

init...

Page 48: Objective-C Guide

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

Page 49: Objective-C Guide

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:

Page 50: Objective-C Guide

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 {

Page 51: Objective-C Guide

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

Page 52: Objective-C Guide

initWithName: init

Class B

Class A

– init

– initWithName:

init initWithName:init

init initWithName:

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

initWithName:init

Page 53: Objective-C Guide

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:

Page 54: Objective-C Guide

– 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

Page 55: Objective-C Guide

– 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;

Page 56: Objective-C Guide

+ (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 *

Page 57: Objective-C Guide

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

Page 58: Objective-C Guide

helpOut: assistant

- setAssistant:anObject{ assistant = anObject;}

assistant

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

assistant helpOut:

Page 59: Objective-C Guide

id formatter = [receiver formattingService];

Page 60: Objective-C Guide

- (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

Page 61: Objective-C Guide

@protocol MyProtocol

- (void)requiredMethod;

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

@required- (void)anotherRequiredMethod;

@end

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

NSObjectNSObject

Page 62: Objective-C Guide

@protocol()

Protocol *myXMLSupportProtocol = @protocol(MyXMLSupport);

@protocol()

■ @protocol()

@interface ClassName : ItsSuperclass < protocol list >

@interface ClassName ( CategoryName ) < protocol list >

@interface Formatter : NSObject < Formatting, Prettifying >

Page 63: Objective-C Guide

@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;

Page 64: Objective-C Guide

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)] ) ...

Page 65: Objective-C Guide

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

Page 66: Objective-C Guide
Page 67: Objective-C Guide

@property @property@interface @property

Page 68: Objective-C Guide

@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

Page 69: Objective-C Guide

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

Page 70: Objective-C Guide

■ 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

Page 71: Objective-C Guide

@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

Page 72: Objective-C Guide

@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

Page 73: Objective-C Guide

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;

Page 74: Objective-C Guide

- (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

Page 75: Objective-C Guide

__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

Page 76: Objective-C Guide

@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

Page 77: Objective-C Guide

@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

Page 78: Objective-C Guide

@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

Page 79: Objective-C Guide

@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

Page 80: Objective-C Guide

@private

NSArray

super

Page 81: Objective-C Guide

windowWillClose: NSObjectNSWindow

NSObject

■ super

NSObjectself

NSObject

@implementation

@interface MyObject : NSObject{

Page 82: Objective-C Guide

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:

Page 83: Objective-C Guide

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"];

Page 84: Objective-C Guide

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;

Page 85: Objective-C Guide

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;}

Page 86: Objective-C Guide
Page 87: Objective-C Guide

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

Page 88: Objective-C Guide

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 }

Page 89: Objective-C Guide

}

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; }}

Page 90: Objective-C Guide
Page 91: Objective-C Guide

■ idid

id

id

id

Rectangle *thisObject;

thisObject

id

Page 92: Objective-C Guide

id

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

iddisplay

thisObject

[thisObject display];

id

Shape *aShape;Rectangle *aRect;

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

aRect aShapeaShape aRect

Page 93: Objective-C Guide

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;

Page 94: Objective-C Guide

- (int)worry;

worrydouble worry int

worry double int

Page 95: Objective-C Guide

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);

Page 96: Objective-C Guide

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

Page 97: Objective-C Guide

performSelector: id

NSControl

NSButtonCell NSMatrix

NSButtonCellNSButtonCell

NSButtonCell

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

NSObject performSelector:withObject:id

NSButtonCellNSButtonCell

Page 98: Objective-C Guide

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:

Page 99: Objective-C Guide

NSException NSError

-fobjc-exceptions

@try @catch @throw@finally

■ @try

■ @catch() @try@catch()

■ @finally

■ @throwNSException

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

@try { [cup fill];}

Page 100: Objective-C Guide

@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];

Page 101: Objective-C Guide

@throw exception;

@catch() @throw

NSExceptionNSException

NSException

Page 102: Objective-C Guide
Page 103: Objective-C Guide

-fobjc-exceptions

@synchronized()

@synchronized()

@synchronized()

@synchronized() self

self

self

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

initialize

Page 104: Objective-C Guide

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

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

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

@synchronized()

@synchronized()

Page 105: Objective-C Guide
Page 106: Objective-C Guide

BAProxy

forB

conformsToProtocol: @protocol()

NSProxy NSConnection

onewayinoutinoutbycopy

Page 107: Objective-C Guide

byref

- (BOOL)canDance;

canDance

initial message

return information

AProxy

forB

B

oneway

- (oneway void)waltzAtWill;

oneway constoneway float oneway id oneway void

Page 108: Objective-C Guide

- 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 *

Page 109: Objective-C Guide

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

Page 110: Objective-C Guide

bycopy byreffoo

@Protocol foo- (bycopy)array;@end

foo

Page 111: Objective-C Guide

/* 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;

Page 112: Objective-C Guide

@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!

Page 113: Objective-C Guide

@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

Page 114: Objective-C Guide

#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

Page 115: Objective-C Guide

[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

Page 116: Objective-C Guide
Page 117: Objective-C Guide

[receiver message]

■ self

■ super

objc/objc.h

id

Class

SEL

idIMP

YES NO

BOOL char

BOOL

id

Page 118: Objective-C Guide

objc.h

(id)0nil

(Class)0Nil

(BOOL)0NO

(BOOL)1YES

#include#import

//

@interface

@implementation

@protocol

@end

@private

@protected

@public

Page 119: Objective-C Guide

@protected

@try

@throw

@try@catch()

@try@finally

@property

@synthesize

@dynamic

@class

@selector(method_name)

@protocol@protocol(protocol_name)

@encode(type_spec)

NSString@"string"

Page 120: Objective-C Guide

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

Page 121: Objective-C Guide

#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

Page 122: Objective-C Guide

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));

Page 123: Objective-C Guide

@end

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

.m.h

Page 124: Objective-C Guide
Page 125: Objective-C Guide
Page 126: Objective-C Guide

initialize

conformsTo: conformsToProtocol:

id

Ivar objc_ivar_list

class_getInstanceMethodclass_getClassMethod

method_getArgumentInfo

Page 127: Objective-C Guide
Page 128: Objective-C Guide
Page 129: Objective-C Guide

NSData

Page 130: Objective-C Guide

NSView

init...

selfinit...

super

@protocol

id

NSObject

NSObject

Page 131: Objective-C Guide

NSApplication

id

Page 132: Objective-C Guide

SEL

Page 133: Objective-C Guide

//@""

_cmd__cplusplus__OBJC__

alloc

allocWithZone:

BOOLbycopybyref

.c

@catch()

Class@class

self

Page 134: Objective-C Guide

//

conformsToProtocol:

@encode()@end

@finally

.h

id

IMP@implementation

#importin#include#include #import

initinitialize

inout

Page 135: Objective-C Guide

@interface

isaisKindOfClass:isMemberOfClass:

.m

super

.mm

NilnilNONSClassFromString

NSSelectorFromStringNSStringFromSelector

Page 136: Objective-C Guide

onewayout

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

@private

@protected@protocol

@public

respondsToSelector:

SEL@selector()

self

super

@synchronized()

this@throw@try

Page 137: Objective-C Guide

unsigned int

void

YES