Objective C
Основан на C Объектно-ориентированный Использует сообщения Динамический Протоколы Интроспекция
id Специальный тип, являющийся указателем на произвольный объект. [receiver message]; nil может принимать любые сообщения, возвращает тоже nil
Сообщения [myRect setOrigin:30.0 :50.0]; [myRect setWidth:10.0 height:20.0]; [myObject makeGroup: obj1, obj2, obj3, obj4, nil]; [myRect setColor:[otherRect color]]; [Rect newrect]; Rect *rect = [Rect new];
Создание новых ClassName : SuperClass { instance variable declarations } method
@interface Rect : NSObject { float width; float height; BOOL isFilled; NSColor * color;
@interface Rect : NSObject { float x, y; float width; float height; BOOL isFilled; NSColor * color; } + newRect; - (void) display; - (float) width; - (float) height; - (float) area; - (void) setWidth: (float) theWidth; - (void) setHeight: (float) theHeight; - (void) setX: (float) theX y: (float)
#import Rect + newRect { Rect * rect = [[Rect alloc] init]; [rect setWidth: 1.0f]; [rect setHeight: 1.0f]; [rect setX: 0.0f y: 0.0f]; return [rect autorelease]; } - (float) width { return width; } - (float) height { return height; } - (float) area { return [self width] * [self height]; } - (void) setWidth: (float) theWidth { width = theWidth; } - (void) setHeight: (float) theHeight { height = theHeight; } - (void) setX: (float) theX y: (float) theY { x = theX; y = theY;
@interface Worker : NSObject { char * int age; char * int job; float id boss }
Как работают сообщения [object msg] -> objc_msgSend id objc_msgSend(id theReceiver, SEL theSelector,...) object -> isa -> class object -> superclass, dispatch table
Селекторы SEL setWidth SEL setPos SEL setWidth = NSSelectorFromString ); NSString * methodName = NSStringForSelector ( setPos ); if ( [anObject ) [anObject setWidth:1];
self super
ProtocolName Serializable - (id) initWithCoder: (NSCoder *) coder; - (void) encodeWithCoder: (NSCoder *)
MyProto if ( [myObject (Serializable)] ) [myObject encodeWithCoder: myCoder]; id myObject; Shape *myObject;
Создание и уничтожение объектов id anObject = [[Rectangle alloc] init]; id anObject = [Rectangle alloc]; [anObject init]; id anObject = [Rectangle new];
init - initWithName: (const char *) theName // designated initializer { [super init]; // call inherited method name = strdup ( theName ); } - init { return [self initWithName: ""]; }
retain, release id object = [MyClass new]; … [object release]; id object = [[object getResult] retain]; … [object release];
dealloc - (void) dealloc {... [super dealloc]; }
NSAutoreleasePool NSAutoreleasePool *pool = [NSAutoreleasePool new]; … [pool release];
autorelease + (Rect *) newRect { Rect *rect = [Rect new]; [rect autorelease]; return rect; }