Sunteți pe pagina 1din 133

.

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
nil

id

id

id
objc/objc.h

0 id nil

int

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

float

double

long double

long long

nil

sizeof(void*)
0

nil

0.0

nil
nil
id anObjectMaybeNil = nil;
// this is valid
if ([anObjectMaybeNil methodThatReturnsADouble] == 0.0)
{
// implementation continues...
}

nil
void
nil

sizeof(void*)
nil

nil
nil
sizeof(void*)

primaryColor
otherRect

primaryColor

isFilled

display

display

id

copy

copy

display

.
[]

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

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
aProperty

aVariable
aVariable

anObject.name = @"New Name";

setName

anObject
setName

@"New Name"
name

void
xOrigin = aView.bounds.origin.x;

bounds
NSRect

xOrigin
bounds

origin.x

setName:

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
to readonly property 'readonlyProperty'

warning: assignment
readwrite

NSMatrix
NSText
NSArray

NSWindow

NSWindow

NSDictionary

NSFont

NSObject

NSObject
Graphic
Image

Text
Shape
Line

Rectangle

Circle

Square

NSObject
NSObject
NSObject
NSObject

NSObject

NSObject

NSObject
NSObject

NSObject
NSObject
NSObject

NSObject

isa
isa

Class
NSPoint
NSColor
Pattern
...
float
float
BOOL
NSColor
...

isa;
origin;
*primaryColor;
linePattern;
width;
height;
filled;
*fillColor;

declared in NSObject
declared in Graphic
declared in Shape

declared in Rectangle

NSObject

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
isMemberOfClass:

isKindOfClass:

NSObject
int versionNumber = [Rectangle version];

id
id aClass = [anObject class];

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
NSTextFieldCell
NSCell
NSMatrix

NSButtonCell

NSMatrix

NSMatrix
NSMatrix
NSCell
NSCell

NSMatrix
NSMatrix
NSMatrix

NSMatrix
NSCell
NSCell
NSMatrix
[myMatrix setCellClass:[NSButtonCell class]];

NSMatrix

NSMatrix
setCellClass:

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

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

- makeGroup:group, ...;

id

#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
@private

@public

private_extern
@private
@protected

The class that


declares the
instance variable

@public

@private

@protected
A class that
inherits the
instance variable

@public

Unrelated code

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

evaluation

name job

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

super
super

super
objc_msgSend
super

self

self

super
negotiate
makeLastingPeace

negotiate

superclass
High

negotiate

superclass
Mid

negotiate
makeLastingPeace

superclass
Low

negotiate

makeLastingPeace
makeLastingPeace
self

negotiate

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

negotiate
super

self

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

negotiate
makeLastingPeace
negotiate
super
makeLastingPeace

negotiate

negotiate

negotiate

super
negotiate

makeLastingPeace

negotiate
negotiate

super

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

super

init
init
init
init

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

super

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
self

alloc
rectangleOfColor:
array

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

NSArray

id anObject = [[Rectangle alloc] init];

NSObject

alloc

alloc

allocWithZone:

NSObject
allocWithZone:

isa
0

init
NSView
initWithFrame:
init...
isa

init...

init
NSObject init

NSObject
isa
self NSObject

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
NSMutableString
NSMutableString
NSString

initWithFormat:
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]
dealloc

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

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

initWithName:
init

initWithName:

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:fromFile:

initWithName:

init
Class B

initWithName:

Class C

initWithName:
initWithName:fromFile:

init

initWithName:fromFile:
super
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:

+ (id)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc;


+ (id)stringWithFormat:(NSString *)format, ...;

NSArray
+ (id)array;

NSString

+ (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
@required
@optional
@required
@required

@optional

@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:
conformsToProtocol:

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

respondsToSelector:
isKindOfClass:

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

@interface

@property @property
@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
setFoo:

foo
readonly

getter=getterName

setter=

setter=setterName
void
readonly

setter=

getter
is

readwrite
@implementation

@synthesize

readonly
readonly
@synthesize

@implementation

assign
NSInteger
retain

CGRect

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;

age

firstName lastName
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

readonly

readwrite

readwrite
@synthesize

NSString
readonly

NSArray
NSDictionary
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

name

gratuitousFloat

nameAndAge

next

dynamic
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

readonly
value

@interface MyInteger : NSObject


{
NSInteger value;
}
@property(readonly) NSInteger value;
@end
@implementation MyInteger

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:

setNumber:
setNumber:

@implementation

@implementation

for ( Type newVariable in expression ) { statements }

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

NSFastEnumeration
statements

nil

NSEnumerator

NSFastEnumeration
NSArray NSDictionary
NSArray

NSEnumerator
NSDictionary
NSDictionary

NSSet
NSSet

NSManagedObjectModel
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

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
}

NSEnumerator

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
init

id

alloc

id

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

NSObject

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

BOOL solid = [myRectangle isFilled];

isFilled

[myRectangle display];

worry
- (double)worry;

double

- (int)worry;

worry
double
worry

worry
double

int
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

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

[friend gossipAbout:aNeighbor];

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

helper

getTheReceiver
request

getTheSelector

SEL

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 cant 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
for
B

conformsToProtocol:

@protocol()

NSProxy

oneway
in
out
inout
bycopy

NSConnection

byref

- (BOOL)canDance;

canDance

Proxy
for
B

initial message

B
return information

oneway

- (oneway void)waltzAtWill;

oneway
oneway float

const
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

inout

char *

in

out

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
id

byref

bycopy

byref
foo

@Protocol foo
- (bycopy)array;
@end

foo

/* Hello.mm
* Compile with: g++ -x objective-c++ -framework Foundation Hello.mm
*/
#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;

-o hello

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

Hello *hello = new Hello("Bonjour, monde!");


[greeting sayGreeting:hello];

// > Bonjour,

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

__cplusplus

__OBJC__

class Base { /* ... */ };


@interface ObjCClass: Base ... @end // ERROR!
class Derived: public ObjCClass ... // ERROR!

world!

monde!

@interface Foo {
class Bar { ... } // OK
}
@end
Bar *barPtr; // OK

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

fobjc-call-cxx-cdtors

alloc

fobjc-call-cxx-cdtors
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
Class0
Class1
Class1

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

...
@end

id Class SEL IMP

this

this

BOOL

self

self
super
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
BOOL

id
YES
BOOL

id

NO
char

objc.h

nil

(id)0

Nil

(Class)0

NO

(BOOL)0

YES

(BOOL)1

#import

//

@interface
@implementation
@protocol
@end

@private
@protected
@public

#include

@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" ...


@"stringN"

NSString

@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 <
declarations of required
@optional
declarations of optional
@required
declarations of required
@end

protocol list >


methods
methods
methods

@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

unsigned

int
unsigned int

self
_cmd
self

super

super

void

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

self

@end

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

.m
.h

initialize

conformsTo:

conformsToProtocol:

id

objc_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

//
@""
_cmd
__cplusplus
__OBJC__

.c

@catch()

alloc
allocWithZone:
Class
@class

self

@finally

.h
//

conformsToProtocol:
id

IMP
@implementation

#import
in
#include
#include

@encode()
@end

init
initialize
inout

#import

super

@interface
.mm
isa
isKindOfClass:
isMemberOfClass:

.m

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

S-ar putea să vă placă și