Download as pdf or txt
Download as pdf or txt
You are on page 1of 137


.m
.c
.mm

@interface ( )

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


id
id

typedef struct objc_object {


Class isa;
} *id;

isa

typedef struct objc_class *Class;

isa isa

id

id anObject;

id int
int

nil id 0 id nil
objc/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];

isFilled
YES myRectangle NO

BOOL isFilled;
isFilled = [myRectangle isFilled];

[myRectangle setPrimaryColor:[otherRect primaryColor]];

nil
nil

■ 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 valid
if ([anObjectMaybeNil methodThatReturnsADouble] == 0.0)
{
// implementation continues...
}

nil
void sizeof(void*)
nil nil nil

nil
sizeof(void*)

primaryColor
otherRect

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 z
z
z
z BOOL
readonly
nil
nil

// each member of the path is an object


x = person.address.street.name;
x = [[[person address] street] name];

// the path contains a C struct


// will crash if window is nil or -contentView returns nil
y = 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 aVariable
aProperty aVariable

anObject.name = @"New Name";

setName anObject @"New Name"

setName name setName:


void

xOrigin = aView.bounds.origin.x;

bounds xOrigin origin.x


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

11 anObject.integerProperty anotherObject.floatProperty
setIntegerProperty:
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 flag
flag

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

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

readonly warning: assignment


to readonly property 'readonlyProperty'
readwrite

NSMatrix NSWindow NSDictionary NSFont


NSText
NSArray NSWindow
NSObject

NSObject

Graphic

Image Text

Shape

Line Rectangle Circle

Square

NSObject

NSObject
NSObject

NSObject
NSObject

NSObject

NSObject
NSObject

NSObject
NSObject

NSObject NSObject

isa NSObject
isa

Class isa; declared in NSObject


NSPoint origin; declared in Graphic
NSColor *primaryColor;
Pattern linePattern; declared in Shape
...
float width;
float height;
BOOL filled; declared in Rectangle
NSColor *fillColor;
...
NSObject

display
display
display
NSObject
NSObject

NSView

sizeof

int i = sizeof(Rectangle);

id

Rectangle *myRectangle;

id
id

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

alloc
0 isa
init

myRectangle = [[Rectangle alloc] init];

myRectangle
alloc
init
alloc init

initWithPosition:size:

NSMatrix
NSCell
NSMatrix

NSMatrix

NSCell

NSCell

NSObject

NSCell

NSBrowserCell NSActionCell

NSButtonCell NSTextFieldCell NSSliderCell NSFormCell

NSMenuCell

NSCell NSButtonCell
NSTextFieldCell
NSCell NSMatrix

NSMatrix

NSMatrix
NSMatrix
NSCell NSMatrix
NSCell NSMatrix
NSMatrix

NSMatrix NSMatrix
NSCell setCellClass:
NSCell NSMatrix

[myMatrix setCellClass:[NSButtonCell class]];

NSMatrix
int MCLSGlobalVariable;

@implementation MyClass
// implementation continues

static
static

static MyClass *MCLSSharedInstance;

@implementation MyClass

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

static

initialize
initialize
initialize
initialize

initialize

initialize initialize
initialize
initialize
initialize
initialize initialize
initialize

initialize

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

initialize
initialize initialize

NSObject

NSObject

NSObject

Rectangle *anObject;

anObject

id class
isKindOfClass:

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


...

NSClassFromString

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

nil

class
class

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

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


.m

.h Rectangle.h
Rectangle.m

@interface
@end

@interface ClassName : ItsSuperclass


{
instance variable declarations
}
method declarations
@end
NSObject

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

+ alloc;

- (void)display;

radius
radius

- (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.m
Rectangle.h


#import "ClassName.h"

@implementation ClassName
method 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 @package @public


@private
private_extern

@private
@protected @public

The class that


declares the @private
instance variable

@protected

A class that
inherits the @public
instance variable

Unrelated code

age evaluation name job wage


boss

@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

reposition
setOrigin::
setOrigin:: reposition
self super reposition

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

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

self super reposition


self

super self

■ self

■ super
super

super
objc_msgSend
super
self super

negotiate
makeLastingPeace negotiate

superclass

High – negotiate

superclass

Mid – negotiate
– makeLastingPeace

superclass

Low – negotiate

makeLastingPeace
makeLastingPeace negotiate
self

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

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

negotiate
makeLastingPeace
negotiate

super
makeLastingPeace negotiate

negotiate

■ negotiate

■ super makeLastingPeace
negotiate

negotiate

negotiate

super

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

super init
init
init super
init

- (id)init
{
if (self = [super init]) {
...
}
}
super
isa
alloc allocWithZone: NSObject
super

super
self

self
self super
self
self

+ (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 alloc
self rectangleOfColor:
array NSArray
NSMutableArray

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

id anObject = [[Rectangle alloc] init];

NSObject
NSObject alloc allocWithZone:

alloc allocWithZone: isa


0

init
NSView
initWithFrame:

init... NSObject
isa 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
...

isa
0

■ init
initWithFormat: initWithObjects:
initWithObjectsAndKeys:

■ id

id
NSString
initWithFormat: NSMutableString
NSString NSMutableString NSString

NSObject init

■ self

■ self
nil

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


release
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

– init

Class A

Class B – initWithName:

init initWithName:
init
init initWithName:

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

initWithName:
init
– init

Class A

– init

Class B – initWithName:

initWithName:

super

initWithName:fromFile:
init initWithName:
initWithName: initWithName:fromFile:

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

init initWithName:
initWithName:fromFile:
– init

Class B – initWithName:

Class C – initWithName:

– initWithName:fromFile:

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

super
self

self
super
– init

Class A

– init

Class B – initWithName:

Class C – initWithName:

– initWithName:fromFile:

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;

NSMatrix
NSCell
NSCell NSMatrix
NSMatrix
NSMatrix

@protocol

@protocol ProtocolName
method 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

NSObject
NSObject
@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 : foo
setFoo:
readonly setter=

getter=getterName
setter=setterName

void
readonly setter=

getter
is

readwrite

@implementation @synthesize

readonly

readonly @implementation
@synthesize

assign

NSInteger CGRect

retain assign
retain
retain assign
release

retain

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

copy
assign
release
copy
NSCopying
■ assign
retain copy


assign retain copy NSCopying

nonatomic

nonatomic

[_internal lock]; // lock using an object-level lock


id result = [[value retain] autorelease];
[_internal unlock];
return result;

nonatomic

__attribute__

@property CGFloat x
AVAILABLE_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 @dynamic
readonly

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


age 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
NSString
NSArray 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

copy
copy

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

dealloc
dealloc
assign
assign

dealloc
nil
- (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 MyInteger
readonly 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

retain
assign copy nonatomic

// assign
property = newValue;

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

// copy
if (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

NSArray
NSArray
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: NSObject
NSWindow

NSObject

■ super

NSObject
self
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

■ void
static

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 deallocated
NSString *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_RETAIN
overview
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

NSFastEnumeration
NSArray NSDictionary NSSet
NSEnumerator NSArray NSSet

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

■ id
id

id

id

id

Rectangle *thisObject;

thisObject

id
id

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

id
display
thisObject

[thisObject display];

id

Shape *aShape;
Rectangle *aRect;

aRect = [[Rectangle alloc] init];


aShape = aRect;

aRect aShape
aShape aRect
id
id 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;

worry
double worry int

worry double int


SEL

SEL
0 SEL

@selector()
setWidth:height: setWidthHeight

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

SEL @selector()

NSSelectorFromString

setWidthHeight = NSSelectorFromString(aBuffer);

NSStringFromSelector

NSString *method;
method = NSStringFromSelector(setWidthHeight);
display
display

display
display

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 getTheReceiver
request
getTheSelector
performSelector: id

NSControl

NSButtonCell NSMatrix

NSButtonCell
NSButtonCell

NSButtonCell

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

NSObject performSelector:withObject:
id

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

■ @throw
NSException

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

NSException
NSException
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()
Proxy
A for B
B

conformsToProtocol: @protocol()

NSProxy NSConnection

oneway
in
out
inout
bycopy
byref

- (BOOL)canDance;

canDance

initial message
Proxy
A for B
B return information

oneway

- (oneway void)waltzAtWill;

oneway const
oneway 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;

inout
const in inout

in in out
inout

char *
out inout

- getTuneTitle:(out char **)theTitle;

- adjustRectangle:(inout Rectangle **)theRect;

- danceWith:(id)aPartner;

danceWith: id
aPartner

danceWith:

bycopy

- danceWith:(bycopy id)aClone;

bycopy

- (bycopy)dancer;

out

- getDancer:(bycopy out id *)theDancer;

bycopy

byref

byref

bycopy byref
id
bycopy byref
foo

@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-cdtors
alloc class_createInstance

dealloc
object_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 super
this this self super

oneway
in out inout bycopy

class
NSObject class
[foo class]; // OK

class

NSObject *class; // Error

@interface
foo @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

IMP id

BOOL YES NO
BOOL char

id
objc.h

nil (id)0

Nil (Class)0

NO (BOOL)0

YES (BOOL)1

#import #include

//

@interface

@implementation

@protocol

@end

@private

@protected

@public
@protected

@try

@throw

@catch() @try

@finally
@try

@property

@synthesize

@dynamic

@class

@selector(method_name)

@protocol(protocol_name)
@protocol

@encode(type_spec)

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

@synchronized()

@interface

#import "ItsSuperclass.h"

@interface ClassName : ItsSuperclass < protocol_list >


{
instance variable declarations
}
method declarations
@end

#import "ClassName.h"

@implementation ClassName
method 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
@optional
declarations of optional methods
@required
declarations 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 int
unsigned 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_getInstanceMethod
class_getClassMethod

method_getArgumentInfo
NSData
NSView

@protocol

init...

self
init...

super

id

NSObject

NSObject
NSApplication

id
SEL
BOOL
bycopy
byref

//
@""

.c
_cmd
__cplusplus
__OBJC__
@catch()

alloc

allocWithZone:
Class
@class

self
@finally

.h

//

conformsToProtocol:

id

IMP
@implementation

#import
in
#include
#include #import

@encode()
@end
init
initialize

inout
super

@interface
.mm

isa
isKindOfClass:
isMemberOfClass:

Nil
nil
.m NO
NSClassFromString

NSSelectorFromString
NSStringFromSelector
oneway
out

performSelector:
performSelector:withObject:
performSelector:withObject:withObject: SEL
@selector()

self

@private

@protected
@protocol

super

@public

@synchronized()

this
@throw
@try

respondsToSelector:
unsigned int

void

YES

You might also like