You are on page 1of 21

Nguyn Giang Nam

Learn Objective C

namng174@gmail.com 092.881.3468

Gii thiu
Ngn ng lp trnh Objective C (ObjC) l mt ngn ng lp trnh c xy dng da trn nn tng ngn ng C. Mi th lm vic trong C u lm vic c trong ObjC. ObjC thm vo nhiu tnh nng mi t C, thm lp trnh hng i tng (Object-Oriented Programming, OOP) v Smalltalk message passing. Objective C l ngn ng c bin dch thnh m my (native machine code) ging vi C/C++, v do n nhanh hn so vi nhng ngn ng chy trn my o nh Java, Python hoc Ruby. Mt khc, ObjC c nhiu tnh nng lm cho n linh ng hn C++. ObjC h tr c nh kiu tnh static typing v nh kiu ng dynamic typing, tu thuc vo bin c khai bo. Nhng v hiu nng lm vic th ObjC km hn C++. Ngn ng Objective C c ra mt vo nm 1983 bi Brad Cox v Tom Love.

Source Code
Trong Objective C khng s dng namespaces ging nh cc ngn ng khc, thay vo phn bit cc class n t cc frameworks khc nhau ObjC s dng name prefixes tn ca class. Cc tp tin c t chc bng cch tng t nh vi C/C++: tp tin tiu (*.h) cha cc khai bo, tp tin m ngun (*.m) - thc hin vit cc dng lnh trin khai. (*.h) ngha l header, (*m) ngha l message hoc l methods. Chng trnh thc thi bt u vi hm int main(). c th s dng frameworks hoc cc class t nh ngha cn s dng t kho #include.

Class & Object


Chng c v ging nhau, nhng khng phi l mt. Class l mt nh ngha, trong khi Object l mt th hin ca Class to. Class nh mt bn v k thut trong khi Objects l i tng tn ti thc s. C php to ra mt class trong Objective C l rt n gin. N bao gm hai phn: - Class interface thng c lu tr trong tp tin ClassName.h, nh ngha cc instance variables v public method. - M ngun thc thi c vit trong tp tin ClassName.m. Objective C s dng n k tha. Sau y l c php thng dng to ra class:

Class & Object


Class Header (.h) #import "AnyHeaderFile.h" @interface ClassName : SuperClass { // declare instance variables } // define properties // define methods (including any // custom initializers) @end Class Implementation (.m) #import "YourClassName.h @implementation ClassName // synthesize properties // implement methods (including any custom initializers, and dealloc) @end

Class & Object


Cch khi to Object (Class instance): //cch th nht: ClassName * myClass = [[ClassName alloc] init]; //cch th hai: ClassName * myClass = [ClassName new]; //cch th ba: ClassName * myClass = [[ClassName alloc] initWithSomething:something]; //myClass c s dng cho n khi gi release: [myClass release]; // khng cn thit vi ARC

Variable & Property


Variable
Variable access (quyn truy cp) c thit lp bi cc t kho @public, @private, @protected; cc t kho s dng c t trc nhm variable cn thit lp. Thit lp mc nh l @protected. truy cp instance variable s dng -> v d: person->name . Nu bn mun s dng static variable trong class, khi khai bo bn s dng t kho static trong header file, bn ngoi vng ca @interface (v d: static anytype staticVariable;). Cch khai bo variables: anytype myVariable; @public anytypeA myVariableA; anytypeB myVariableB;

Variable & Property


Property
Trong @interface, khai bo nh sau @property anytype age;. Tng ng vi vic khai bo getter: (anytype) age; (trong ObjC getter khng c tin t get) v setter: (void) setAge: (anytype)age. Trong @implementation, s dng @synthesize age;, tng ng vi to ra cc lnh thc thi getter v setter mc nh. C th to ra cc lnh thc thi tu bin cho getter v setter bng vic overide li setter v getter m khng s dng @synthesize. trnh nhm ln gia variable v property, cc property khng th s dng -> truy cp m s dng obj.age hoc [obj age]. Cc property c th c cc thuc tnh tu chn bng cch thm vo sau t kho @property, nh l: @property (readonly) anytype age; C th tm hiu thm cc thuc tnh t ti liu apple cung cp.

Method
Cch nh ngha mt method: - (void)doIt; hoc - (anytype)doIt; + (void)doIt; hoc + (anytype)doIt; //class method - (anytype)doItWithA:(anytype)a; - (anytype)doItWithA:(anytype)a andB:(anytype)b; Cch trin khai method: - (anytype)doItWithA:(anytype)a andB:(anytype)b { // Do something with a and b... return retVal; }

Method
Mt iu khc bit v method trong Objective C l cc tham s c a ra cng vi khi nim label, c s dng trong vic gi hm (vi Objective C vic gi hm c nh ngha l gi mt message ti object k tha t Smalltalk). Label thc s c hnh thnh t tn y ca method. Bi vy method trc c label l doItWithA:andB:. Method trong Objective C khng th overload bng kiu d liu ca tham s nh trong cc ngn ng thng dng, nn khng th cng lc c hai method doIt(typeA) v doIt(typeB). Trong Objective C, khi gi mt message (gi mt method) khng tn ti s khng a ra li lc bin dch, nhng s a ra exception trong lc thc thi. C th bt v x l vi c php try...catch. Method i khi c s dng vi khi nim l selector.

Category
Trong ObjC, ngoi vic k tha t cc class, bn cng c th thm code vo cc class hin c. C th pht trin cc class hin c m khng cn phi thay i code trong class , tuy n khng mnh m nh Ruby (v d nh bn khng th thm cc instance varibale mi) nhng iu ny thc s rt tuyt vi. y n c gi l category bi v nu c mt class nhiu method, c th phn chia cc method ca n thnh nhiu loi v t chng trong cc file khc nhau. Di y l cch khai bo mt category: @interface ExistingClass (SomeNewName) // methods @end Sau , include c header c v header mi vo ni bn mun s dng, v bn c mt class vi cc method mi c thm vo.

Data types
ObjC c c hai kiu d liu l primitive v object. Vi kiu object ch c kiu con tr v khng c kiu gi tr. Cc kiu d liu primitive (c bn): char, int, float, double, short, long, BOOL. ObjC khng khuyn khch s dng cc kiu d liu primitive, c cc kiu thay th v d nh NSInteger, NSUInteger, hoc CGFloat (y l cc phin bn c kin trc an ton ca int, unsigned int, float). Ngoi ra cn c mt class l NSNumber s dng cho vic boxing/unboxing kiu pimitive khi cn chuyn thnh kiu d liu object. Kiu d liu logic c gi l BOOL, v gi tr khng ging nh cc ngn ng khc True/False m ObjC s dng YES/NO J. Kiu Null gi l nil. i vi kiu con tr, nil c vit l Nil. Tng t nh NSNumber cho int, class dng cho nil l NSNull. Kiu chui trong ObjC l NSString.

Loops
Cu trc ca lnh vng lp trong ObjC khng khc bit nhiu vi cc ngn ng khc. ObjC c cc lnh lp for, while, do-while, for-each. Sau y l c php ca cc vng lp:

for (<#initialization#>; <#condition#>; <#increment#>) { <#statements#> } for (int i=0; i<n; i++) { //Statements here... }

Loops
while (<#condition#>) { <#statements#> } while (a<b) { //Statements here.. }

do { <#statements#> } while (<#condition#>); for (<#type *object#> in <#collection#>) { <#statements#> }

do { //Statements here.. } while (a<b); for (anyType *obj in anyArray) { //Statements here.. }

Conditions
ObjC c cc lnh iu kin: if, switch. Sau y l c php ca cc lnh iu kin:
if (<#condition#>) { <#statements#> } switch (<#expression#>) { case <#constant#>: <#statements#> break; default: break; } if (a<b) { //Statements here.. } switch (i) { case 1: //Statements here.. break; default: break; }

Protocols
Protocol nh ngha mt danh sch cc method bt buc hoc ty chn m cc class chp nhn (adopt) protocol phi thc thi. Cc method khai bo trong protocol cng c th l cc khai bo property. Cc t kha @optional v @required th hin theo ng ngha ca n, nu khng s dng t kha th mc nh l @required. Protocol c s dng trong cc trng hp: - Khai bo cc method d kin s c thc thi. - Khai bo mt interface cho mt object trong khi n i class ca n. - Kho st tng ng gia cc class m khng phi lin quan n cu trc th bc.

Protocols
Cch khai bo mt protocol @protocol FooInterface - (int) foo; - (void) bar; @end Cch class chp nhn (adopt) protocol @interface MyClass: NSObject <FooInterface> Cc method khai bo trong protocol khng cn thit phi khai bo li trong @interface ca class.

Reflection
ObjC c kh nng ng hn C v C++, mc d thc t rng n thc s l mt ngn ng bin dch trc tip m my mnh m. Di y l mt s v d v cc chc nng lin quan n reflection: o isKindOfClass:[MyClass class] - cho bit rng object c class tha k t MyClass hay khng. o isMemberOfClass:[MyClass class] - cho bt rng class ca object c phi l MyClass hay khng. o respondsToSelector:@selector(doIt) - cho bit rng object c method doIt: hay khng. o performSelector:@selector(doIt) - gi method c ch nh doIt: ca object.

Exceptions & debugging


Exceptions lm vic ging nh trong tt c cc ngn ng hin i khc: chng c i din bi cc class k tha (thng thng) t NSException, v s dng cc t kho @try, @catch v @finally chn cc exception ri nm ra bn trong mt block (khi) v x l chng. S dng @throw e nm ra exception e. Hai method c th hu ch trong debug (g li): o NSAssert(x != 0, @"X must not be zero"); - a ra exception nu x bng 0. o NSLog(@result: x = %@", x); - ghi ra mn hnh console chui, v cng ghi mt vi dng vo /var/log/system.log.

Memory management
Cc object trong ObjC l reference counted(tham chiu m). o Cc object bt u vi reference l 1. o Tng reference vi method retain. o Gim reference vi method release, autorelease. o Khi s lng reference l 0, runtime (trnh bin dch) s gi method dealloc. Khi bn nm quyn s hu mt object, khi to object bng cc method m trong tn bt u vi alloc, new hoc copy (v d, alloc, allocWithZone, newObject hoc mutableCopy) hoc gi mt message retain, bn phi c trch nhim gii phng quyn s hu object bng cch s dng release hoc autorelease. Bt k khi no bn nhn c mt object (khng phi t mnh khi to), bn khng c release n. T iOS 4.3 v sau h tr qun l b nh t ng (ARC) vi garbage collector. ARC thc s gip developer d dng loi b memory leaks(tht thot b nh).

retain/release/autorelease
@implementation BankAccount - (NSString *)accountNumber { return [[accountNumber retain] autorelease]; } - (void)SetAccountNumber { if (accountNumber != newNumber) { [accountNumber release]; accountNumber = [newNumber retain]; } } - (void)dealloc { [self setAccountNumber:nil]; [super dealloc]; } @end

You might also like