Objective-C
| : | |
|---|---|
| : |
1986 |
| (): | |
| : | |
| : | |
| : | |
| : | |
| : |
Objective-C, Objective C, ObjC Obj-C - Apple, Smalltalk.
C++, Objective-C ( Objective-C ) . Smalltalk, .
Objective-C GCC . Mac OS X (Cocoa) GNUstep - OpenStep. iOS (Cocoa Touch).
|
|
[]
1980- . «» , . , , . , .
- . , Smalltalk - . .
ObjC 1980 Stepstone. .
, .
Objective-C - . - . Objective-C.
Objective-C , , .
, message-oriented C++ function-oriented. , ( ), ( ) , , Smalltalk-.
, . ( ), ( , ).
.
Objective-C , ( ) instance-, , . .
( ). ( ), . ( , ).
Objective-C gcc llvm ( Windows MinGW cygwin).
runtime- . gcc . runtime- Apple: Apples Objective-C runtime.
runtime- ( ), runtime- Apple.
[]
Objective-C id. id . nil (= NULL).
id . , .
, ( , ).
:
[receiver message];
receiver , message .
C++ nil , (nil).
:
[myRect setOrigin:30.0 :50.0];
() setOrigin::. , . ( ), .
Objective-C , .
[myRect setWidth:10.0 height:20.0];
setWidth: height:.
:
[myObject makeGroup: obj1, obj2, obj3, obj4, nil];
, , , , , id.
float area = [myRect area];
:
[myRect setColor:[otherRect color]];
, Objective-C . ( class objects) ( Abstract Factory).
( ). , ( receiver).
Rect * myRect = [[Rect alloc] init];
Objective-C , . BOOL YES NO ( NextStep, Mac OS X).
Objective-C NextStep. Objective-C, Mac OS X.
NS, NextStep.
NSString . ( ).
, @"my string" NSString, ( , ).
Company instance- name.
@interface Company : NSObject { NSString *name; }
@property (retain) NSString *name;
instance-. 3 .
- getter=getterName, , instance-.
- setter=setterName, , instance-.
/
- readwrite , .
- readonly .
.
- assign . POD- , .
- retain , , instance-, ( ).
- copy , .
GC assign, retain, copy . , , :
@synthesize name;
instance- .
, , .
[]
Objective-C @.
C++, ( h, cpp).
:
@interface ClassName : SuperClass { instance variable declarations } method declarations @end
runtime Apple NSObject, .
:
Apple, NSObject Object (#import <objc/Object.h>).
@interface Rect : NSObject { float width; float height; BOOL isFilled; NSColor * color; } @end
C++ Smalltalk.
. , ( class object, ). C++.
Rect.
@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) theY; @end
, instance- (, width height).
( ). , , id.
, ( ) .
Objective-C oneway, in, out, inout, bycopy byref. . ( NextStep 90- ).
, , :
- makeGroup: (id) object, ...;
Objective-C #include #import, #include, , .
, , ( , ).
@class, , .
@class Shape, Rect, Oval;
:
#import "ClassName.h" @implementation ClassName method implementations @end
Rect, .
#import "Rect.h" @implementation Rect + newRect { Rect * rect = [[Rect alloc] init]; [rect setWidth: 1.0f]; [rect setHeight: 1.0f]; [rect setX: 0.0f y: 0.0f]; return rect; } - (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; } @end
, instance-. , C++, ( ) @private, @protected @public ( C++).
@interface Worker : NSObject { char * name; @private int age; char * evaluation; @protected int job; float wage; @public id boss }
public , -> ( objPtr -> fieldName).
[]
, [object msg] objc_msgSend. - , . . , . , objc_msgSend , . . .
Objective-C isa class object . class object , isa .
class object class object (superclass) dispatch table. , ().
, objc_msgSend dispatch table . , dispatch table . .
( ) , .
«» NSInvocation forwardInvocation:, NSInvocation.
forwardInvocation:, , :
- (void)forwardInvocation:(NSInvocation *)anInvocation { if ( [someOtherObject respondsToSelector: [anInvocation selector]] ) [anInvocation invokeWithTarget: someOtherObject]; else .......... }
dispatch table , . . 32- , .
SEL , .
@selector():
SEL setWidth = @selector(setWidth:); SEL setPos = @selector(setX:y:);
( ) NSSelectorFromString NSStringFromSelector:
SEL setWidth = NSSelectorFromString ( @"setWidth:" ); NSString * methodName = NSStringFromSelector ( setPos );
Objective-C respondsToSelector::
if ( [anObject respondsToSelector: @selector(setWidth:)] )
[anObject setWidth: 200.0];
, ( , , ), performSelector:, performSelector: withObject:, performSelector: withObject: withObject: performSelector::withObject: withObject: withObject:.
[myObject performSelector:sel withObject: nil];
, performSelector: id.
, class. Class.
Class * cls = [anObject class];
NSString * clsName = NSStringFromClass ( cls );
class object :
Class * cls = NSClassFromString ( clsName );
self _cmd.
this, . .
self , :
- (float) area { return [self width] * [self height]; }
self , super. super . super dispatch table , dispatch table .
, super , .
Objective-C ( ).
(self) (_cmd).
methodForSelector: .
typedef float (*WidthFunc)( id, SEL ); typedef void (*SetWidthFunc)( id, SEL, float ); WidthFunc widthFunc = (WidthFunc) [myRect methodForSelector: @selector (width)]; SetWidthFunc setWidthFunc = (SetWidthFunc) [myRect methodForSelector: @selector (setWidth:)]; (*setWidthFunc)( myRect, @selector (setWidth:), 27.5f );
, .
[]
Objective-C ( C++ , ). . , , .
, .
:
@protocol ProtocolName method declarations @end
Serializable :
@protocol Serializable - (id) initWithCoder: (NSCoder *) coder; - (void) encodeWithCoder: (NSCoder *) coder; @end
:
@protocol MyProto <Protocol1, Protocol2, Serializable, Drawable>
, :
@interface MyClass : SuperClass <Protocol1, Protocol2, Serializable, Drawable>
, , conformsToProtocol::
if ( [myObject conformsToProtocol: @protocol (Serializable)] ) [myObject encodeWithCoder: myCoder];
, () ().
, myObject , Serializable Drawable, :
id <Serializable,Drawable> myObject;
, , myObject , Shape Serializable, :
Shape <Serializable> *myObject;
, , .
, Objective-C ( Protocol):
Protocol * myProto = @protocol ( Serializable );
:
@protocol MyProto, Serializable, Drawable;
, MyProto, Serializable Drawable , .
[]
Objective-C , C++ Java.
@try, @catch, @finally @throw.
Cup * cup = [[Cup alloc] init]; @try { [cup fill]; } @catch ( NSException * exc ) { NSLog ( @"Exception caught: %@", exc ); } @catch ( id exc ) { NSLog ( @"Unknown exception caught" ); } @finally { [cup release]; }
@throw, -. Mac OS X/NextStep NSException.
NSException * exc = [NSException exceptionWithName: @"my-exception" reason: @"unknown-error" userInfo: nil]; @throw exc;
@catch- @throw (rethrowing exception).
[]
Objective-C . @synchronized () .
@synchronized () Objective-C ( , self), (mutex).
, - . , , @synchronized ().
, , , (suspended) , . , «» .
, .
- (void) criticalMethod { @synchronized ( self ) { // perfrom modifications to shared objects . . . } }
[]
Objective-C ( new delete). runtime- .
Objective-C NextStep Mac OS X, .
. alloc ( NSObject), ( NSObject, ). isa class object .
, alloc class object- .
( instance-, . .) , init. alloc, , .
id anObject = [[Rectangle alloc] init];
. , :
id anObject = [Rectangle alloc]; [anObject init];
, init ( self).
alloc, init .
, () init , ( C++, , , , ).
init init ( [super init]) .
, init, init, initWithName:, initWithContentsOfFile: . .
init- , designated initializer. init- init .
- (id) initWithName: (const char *) theName // designated initializer { self = [super init]; // call inherited method if (self) { name = strdup ( theName ); } return self; } - (id) init { return [self initWithName: ""]; }
(), NSString , () :
+ (id) stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc + (id) stringWithFormat:(NSString *)format, ...
Mac OS X ( NextStep) reference counting , .
retain ( Foundation , retain).
retain , (), , retain.
, release.
, , .
dealloc, . [super dealloc].
- (void) dealloc { . . . [super dealloc]; }
[]
[]
Objective C « ». Objective C :
- , «alloc», «new» «copy». , alloc, newObject, mutableCopy.
- , , «release» «autorelease». .
- , ( retain), (, «copy»).
Objective C , , .
[]
, Company, workers.
@interface Company : NSObject { NSArray *workers; } -(NSArray*)workers; @end
:
Company *company = [[Company alloc] init]; // ... NSArray *workers = [company workers]; // ... [company release];
Company , ([company release]). , workers , . , .
- Convenience
, convenience ; +className , , Objective C.
Company *company = [Company company]; [company release];
[company release] , autorelease .
company:
+(Company*)company { id ret = [[Company alloc] init]; return [ret autorelease]; }
- autorelease
workers Company. , , workers :
-(NSArray*)workers { NSArray *copy = [[NSArray alloc] initWithArray:workers]; return [copy autorelease]; }
autorelease copy autorelease , release , . , autorelease , release , autorelease .
, , NSData initWithContentsOfURL:options: error: error (NSError **)errorPtr. , , , , .
, . -(void)dealloc. - , .
-(void)dealloc { [workers release]; [super dealloc]; }
, release, dealloc . , dealloc .
dealloc. , . , dealloc , , . .
[] Autorelease pool
Autorelease , release . , autorelease , autorelease.
Cocoa autorelease . -AppKit autorelease .
Autorelease NSAutoreleasePool.
int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; Company *company = [Company company]; NSArray *workers = [company workers]; [pool drain]; return 0; }
autorelease release, drain. release drain . GC drain objc_collect_if_needed.
- Autorelease
Cocoa autorelease . autorelease release.
Autorelease . autorelease , .
[]
Objective C . , , copy, NSObject. copyWithZone NSCopying. NSObject NSCopying -.
: (shallow copy) (deep copy). , , . .
, - NSCopying. , NSCopying:
@interface Company : NSObject <NSCopying> { NSString *name; } @property(retain) NSString *name; -(id)copyWithZone:(NSZone *)zone; @end @implementation Company @synthesize name; -(id)copyWithZone:(NSZone *)zone { id copy = [[[self class] allocWithZone:zone] init]; [copy setName:[self name]]; return copy; } @end
NSCopying, : allocWithZone copyWithZone.
id *copy = [super copyWithZone:zone];
immutable , retain.
-(id)copyWithZone:(NSZone *)zone { return [self retain]; }
[]
Objective-C . Ruby, C#, JavaScript . , . NSObject .
, ( , instance- ), .
, , . :
#import "ClassName.h" @interface ClassName ( CategoryName ) methods declarations @end
:
#import "CategoryName.h" @implementation ClassName ( CategoryName ) methods bodies @end
(property), readwrite :
@interface ClassName { BOOL flag; } @property (assign, readonly) BOOL flag; @end #import "ClassName" @implementation ClassName () // @property (assign, readwrtite) BOOL flag; @end @implementation ClassName @synthesize flag; -(void) someAction { self.flag = YES; } @end
, - , :
@protocol Printable // , -(void) print; @end @interface NSString(Printable) <Printable> // NSString @end @implementation NSString(Printable) // -(void) print { NSLog(@" %@!", self); } @end
- PrintableString NSString
[] Class objects Objective-C runtime
Objective-C class object , , , , instance-.
, , .
class object , NSObject, , , , instance- NSObject.
class object class object () initialize.
class object, , . Singleton initialize static-.
Objective-C runtime Apple, -, ( ).
:
Method class_getInstanceMethod( Class aClass, SEL aSelector ); Method class_getClassMethod ( Class aClass, SEL aSelector ); struct objc_method_list * class_nextMethodList(Class theClass, void ** iterator); void class_addMethods ( Class aClass, struct objc_method_list * methodList ); void class_removeMethods ( Class aClass, struct objc_method_list * methodList ); unsigned method_getNumberOfArguments ( Method method ); unsigned method_getSizeOfArguments ( Method method ); unsigned method_getArgumentInfo ( Method method, int argIndex, const char ** type, int * offset ); Ivar class_getInstanceVariable ( Class aClass, const char * aVariableName );
class_getInstanceMethod (objc_method), instance- .
class_getClassMethod (objc_method), .
class_nextMethodList . .
void * iterator = 0;
struct objc_method_list * methodList;
//
// Each call to class_nextMethodList returns one methodList
//
methodList = class_nextMethodList( classObject, &iterator )
while ( methodList != nil )
{
// do something with the method list here
methodList = class_nextMethodList ( classObject, &iterator );
}
class_addMethods .
class_removeMethods .
method_getNumberOfArguments .
method_getSizeOfArguments , .
method_getArgumentInfo ..
class_getInstanceVariable instance- objc_ivar.
, . @encode ().
char * buf1 = @encode ( int ** ); char * buf2 = @encode ( struct key ); char * buf3 = @encode ( Rectangle );
[]
Apple.[1]
GNUstep open-source Objective-C, Foundation AppKit NextStep Mac OS X.
GNUstep Objective-C , .
gcc Objective-C, GNU/Linux .
Objective-C MS Windows c POSIX (mingw, cygwin) POSIX (MS SFU, Services For Unix, www.microsoft.ru Microsoft Windows UNIX), .
[]
[]
- , . Objective-C 2.0 Mac. = Learn Objective-C on the Mac. .: , 2009. 320 . ISBN 978-5-8459-1607-5
[]
- Introduction to The Objective-C Programming Language (Apple Developer Connection) (PDF) (.)
- Objective-C (.)
- Objective-C: (.)
- Objective-C (.)
- Advanced Flow Control for Objective-C (.)
- Debugging C-Family Languages (.)
- Fun with the Objective-C Runtime (.)
- Objective-C for C++ Programmers (.) (.)
- Steve Kochan on the Evolution of Objective-C (.)
- The Dynamic Languages Renaissance (.)
| Borland Turbo C Clang GCC LCC Pelles C PCC TCC Visual C++ (C++/CLI C++/CX) Watcom C/C++ compiler | |
| glibc dietlibc uClibc Newlib Eglibc Bionic | |
| C- | |
| C++ C# D Objective-C Alef Limbo Go Vala | |
| C | C C++ ( ) Pascal C C - Java |