You are on page 1of 36

Hng dn lp trnh Objective C Trn Ubuntu 1. Mt vi dng v lch s ra i v s pht trin.

Lch s ra i The wiky th Bard Cox v Tom Love (khng bit c thng cha ny khng nhng thy wiki n ni th mnh cng a ra y chc lo Tom Love ny cng c cht t cng sc) thuc Stepstone l cha ca Objective - C. Ngn ng ny c gii thiu nm 1981 v chng ta cng nh rng thp nin 80s ca th k trc l s ln ngi ca khi nim lp trnh OOP cng l giai on cc thnh ca s ra i cc ngn ng OOP trn nn C. Tip tc hon thin trong vi nm n 1986 Cox chnh thc n hnh chun ca Objective - C trong cc cun sch Object-Oriented Programming, An Evolutionary Approach. S k tip ca Steve Jobs Ci tn ny ch nn qua ni ting t cuc i ng cho n s nghip ly lng v c vic ng lm in o cng ng IT th gii cho n chnh bn (chng phi bn cng ang din o v IPhone y !_! ) Khi bi out khi Apple, nm 1988 Steve Jobs mua li bn quyn ca Obejctive - C t Stepstone vit cho ng dng phn cng ca mnh. vi l NeXTstep hay cn gi l OpenStep cng ty lc ny ca Jobs l NeXT. Cho n 1996 khi Apple mua li NeXT th h tip tc s dng cng ngh OpenStep pht trin h iu hnh Mac ca h v xy dng mt lot cng c XCode, Interface Builder .. v cc Cocoa API ra i... n gi th hiu l ti sao li l Objective - C ch khng phi bt c ngn ng no khc build cc App trn nn Apples. 2. Tm hiu ngn ng Ob-c c im c bn. - L ngn ng hng i tng - M rng t C - Nh nhng (khng VM - khng qu thc tp vi friend virtuals vi template vi ....) - Mm do (m rng t C nn bn c th dng C thun cu trc ngoi ra y l ngn ng run-time) - Reflection (c h ch) - nil thay th cho NULL trong C, bi v bn c th gi thng ip cho nil, nhng khng th lm nh vy vi NULL. - BOOL c 2 gi tr l YES v NO ch khng phi l true v false na. - Khi nim methods v message c s dng mang ngha nh nhau i vi ObC theo message c nhng thuc tnh c bit. Mto message c th chuyn ng t obj ti mt obj khc. Vic gi thng ip trn mt obj khng c ngha l obj s thc hin message n c th chuyn tip ti mt obj khc cha bit trc tm li c kh nng p tr thng ip khng trc tip th gin tip. Khi lm vic vi Objective C bn cn ch l bi v n dc base trn nn ca C cho nn vic bn s dng c php C chn ln vi c php chnh thng ca Objective C l hon ton chp nhn, tuy nhn c v hi c chui. Phng thc.

Cch khai bo phng thc trong Objective - C Khng tham s :


Trch dn:

<(kiu tr v)> Tn_phng_thc v d -(void) print; C tham s:


Trch dn:

<(kiu tr v)> Tn_phng_thc :<(kiu)> Tn_Bin :<(kiu)> Tn_Bin; v d: -(void) setDenominator: (int) d; Li gi phng thc: khng tr v: [<i tng> ]; [<i tng> :<(kiu)> ]; [<i tng> :<(kiu)> :<(kiu)> ]; Tr v kt qu: = [<i tng> ]; = [<i tng> :<(kiu)> :<(kiu)> ];

Lp v i tng. Ob-C s dng khi nim Interface v Implementation phn bit file Header v file Source ca C (*.h v *.c) mt lp trong ObC nh ngha l trn mt giao din (.h) cn phn thc thi trn file .m cc bn ch l m v n khc vi C v C++. @interface:
Code:

#import @interface Fraction: NSObject { int numerator; @private int denominator; } -(void) print; -(void) setNumerator: (int) n; -(void) setDenominator: (int) d; -(int) numerator; -(int) denominator; @end v y l phn thc thi. @implementation
Code:

#import "Fraction.h" @implementation Fraction -(void) print { printf( "%i/%i", numerator, denominator ); } -(void) setNumerator: (int) n { numerator = n; }

-(void) setDenominator: (int) d { denominator = d; } -(int) denominator { return denominator; } -(int) numerator { return numerator; } @end
Trch dn:

- S dng #import thay th cho #include (y l c ch thng minh hn #include ca C/C++ bn ch phi thm 1 ln thi ) - ObC ch cho php n k tha. Mc nh tt c cc lp s k tha t NSObject. - Cp @.... v @end l cp gii hn phm vi mt lp. - Cc thuc tnh dc khi bo trong cp { ..... } v khai bo phng thc bn ngoi. - Nu phng thc bt u bng "+" c ngha n l thuc phm vi lp (static), cn nu "-" th n phm vi object. - Cc phm vi truy xut public,protected v private ging nh C++ mc nh l protected. - Cc truy nhp phn t cng s dng ton t "." i vi object v "->" nu l con tr. - khng c cc tm vc truy xut i vi phng thc (tc l trong ObC cc phng thc c cng mt tm vc l public) Exception v handler. Ngn ng cng h ch cc cu trc try - catch - throw - finally ging nh ngn C++ @try @catch - @throw - @finally cch thc s dng cng hon ton tng t. Categories L c im nu bn mun m rng lp bng cch thm mi vo lp mt phng thc. Khi bn lm vic quen vi OOP th bn s thy y l mt trong nhng thuc tnh v cng hu ch ca Objective C, k c ngay khi bn khng c m ngun ca lp nhng bn vn hon ton c th thm phng thc cho lp nh thng thng qua thuc tnh ny. c im ny lm gim i ng k s k tha phc tp trong C++ khi vic k tha ch phc v cho vic thm mi mt phng thc. Mt khc vic chia m ngun trn nhiu files cng gip ch ng k trong vic pht trin.
Code:

#import "Fraction.h" @interface Fraction (Math) -(Fraction*) add: (Fraction*) -(Fraction*) mul: (Fraction*) -(Fraction*) div: (Fraction*) -(Fraction*) sub: (Fraction*) @end File thc thi.
Code:

f; f; f; f;

#import "FractionMath.h"

@implementation Fraction (Math) -(Fraction*) add: (Fraction*) f { return [[Fraction alloc] initWithNumerator: numerator * [f denominator] + denominator * [f numerator] denominator: denominator * [f denominator]]; } -(Fraction*) mul: (Fraction*) f { return [[Fraction alloc] initWithNumerator: numerator * [f numerator] denominator: denominator * [f denominator]]; } -(Fraction*) div: (Fraction*) f { return [[Fraction alloc] initWithNumerator: numerator * [f denominator] denominator: denominator * [f numerator]]; } -(Fraction*) sub: (Fraction*) f { return [[Fraction alloc] initWithNumerator: numerator * [f denominator] denominator * [f numerator] denominator: denominator * [f denominator]]; } @end
Trch dn:

- Tn ca category phi l duy nht - C th thm bao nhiu ln m rng lp t category l khng gii hn nhng vi tn l duy nht. - Thng th b xung bin thnh phn bng category. - C th s dng category to ra cc phng thc private. Nu cn. MyClass.h
Code:

#import @interface MyClass: NSObject -(void) publicMethod; @end MyClass.m


Code:

#import "MyClass.h" #import @implementation MyClass -(void) publicMethod { printf( "public method\n" ); } @end // private methods @interface MyClass (Private) -(void) privateMethod; @end

@implementation MyClass (Private) -(void) privateMethod { printf( "private method\n" ); } @end main.m
Code:

#import "MyClass.h" int main( int argc, const char *argv[] ) { MyClass *obj = [[MyClass alloc] init]; // this compiles [obj publicMethod]; // this throws errors when compiling //[obj privateMethod]; // free memory [obj release]; return 0; } ci ny tht th v phi khng, thc ra y l mt h qu trc tip t c tnh run-time ca Objective C. Protocals: Giao din. y hon ton tng ng vi khi min lp o trong C++ hoc gi l giao din trong C# v Java. Bn thn @protocals khng c s thc thi. Nu lp no cam kt thc thi n th trong phn thc thi s implement cc phng thc m protocals khai bo.
Code:

@protocol Printing -(void) print; @end Fraction.h


Code:

#import #import "Printing.h" @interface Fraction: NSObject { int numerator; int denominator; } -(Fraction*) initWithNumerator: (int) n denominator: (int) d; -(void) setNumerator: (int) d; -(void) setDenominator: (int) d; -(void) setNumerator: (int) n andDenominator: (int) d; -(int) numerator; -(int) denominator;

@end Fraction.m
Code:

#import "Fraction.h" #import @implementation Fraction -(Fraction*) initWithNumerator: (int) n denominator: (int) d { self = [super init]; if ( self ) { [self setNumerator: n andDenominator: d]; } return self; } -(void) print { printf( "%i/%i", numerator, denominator ); } -(void) setNumerator: (int) n { numerator = n; } -(void) setDenominator: (int) d { denominator = d; } -(void) setNumerator: (int) n andDenominator: (int) d { numerator = n; denominator = d; } -(int) denominator { return denominator; } -(int) numerator { return numerator; } -(Fraction*) copyWithZone: (NSZone*) zone { return [[Fraction allocWithZone: zone] initWithNumerator: numerator denominator: denominator]; } @end Complex.h
Code:

#import #import "Printing.h" @interface Complex: NSObject {

double real; double imaginary; } -(Complex*) initWithReal: (double) r andImaginary: (double) i; -(void) setReal: (double) r; -(void) setImaginary: (double) i; -(void) setReal: (double) r andImaginary: (double) i; -(double) real; -(double) imaginary; @end Complex.m
Code:

#import "Complex.h" #import @implementation Complex -(Complex*) initWithReal: (double) r andImaginary: (double) i { self = [super init]; if ( self ) { [self setReal: r andImaginary: i]; } return self; } -(void) setReal: (double) r { real = r; } -(void) setImaginary: (double) i { imaginary = i; } -(void) setReal: (double) r andImaginary: (double) i { real = r; imaginary = i; } -(double) real { return real; } -(double) imaginary { return imaginary; } -(void) print { printf( "%_f + %_fi", real, imaginary ); } @end

main.m
Code:

#import #import "Fraction.h" #import "Complex.h" int main( int argc, const char *argv[] ) { // create a new instance Fraction *frac = [[Fraction alloc] initWithNumerator: 3 denominator: 10]; Complex *comp = [[Complex alloc] initWithReal: 5 andImaginary: 15]; id printable; id copyPrintable; // print it printable = frac; printf( "The fraction is: " ); [printable print]; printf( "\n" ); // print complex printable = comp; printf( "The complex number is: " ); [printable print]; printf( "\n" ); // this compiles because Fraction comforms to both Printing and NSCopyable copyPrintable = frac; // this doesn't compile because Complex only conforms to Printing //copyPrintable = comp; // test conformance // true if ( [frac conformsToProtocol: @protocol( NSCopying )] == YES ) { printf( "Fraction conforms to NSCopying\n" ); } // false if ( [comp conformsToProtocol: @protocol( NSCopying )] == YES ) { printf( "Complex conforms to NSCopying\n" ); } // free memory [frac release]; [comp release]; return 0; }

Properties Thuc tnh gn nh bt c mt ngn ng mi hin i no cng h ch khi nim ny, y l mt khi nim bo ton tnh ng gi ca t tng OOP.

i vi ngn ng ObC c mt s nhng h ch c bit hn mt cht bn khai bo s dng bng @properties cng ging nh nhng ngn ng khc khi bn s dng thuc tnh vi ObC bn s c 2 la chn l @synthesize v @dynamic, vi la chn l @synthesize th mc nhin trnh bin dch s gip bn sinh ra cc phng thc set v get trn thuc tnh. nhng nu bn la chn l @dynamic th mi vic bn phi t lm ly. hy xem code
Code:

#import @interface Photo : NSObject { NSString* caption; NSString* photographer; } - (NSString*) caption; - (NSString*) photographer; - (void) setCaption: (NSString*)input; - (void) setPhotographer: (NSString*)input; @end v
Code:

#import @interface Photo : NSObject { NSString* caption; NSString* photographer; } @property (retain) NSString* caption; @property (retain) NSString* photographer; @end Kiu id id trong ObC gn tng t nh void* trong C. bn khng cn phi bit r kiu ca object khi bn gi phng thc trong ObC iu ny hon ton khc vi C++ bi n gin khi gi phng thc cng ging nh bn truyn thng ip trong ObC. Nu i tng n c phng thc th s p li thng ip m bn truyn (gi phng thc) v phng thc c gi. Cng nguy him y ch .. :( p kiu ng. nhng phng thc di y dng kim tra kiu.
Trch dn:

- (BOOL) isKindOfClass: classObj >> i tng l hu du hoc th hin ca classObj - (BOOL) isMemberOfClass: classObj >> l mt thnh phn ca objClass - (BOOL) respondsToSelector: selector >> i tng c phng thc bi selector + (BOOL) instancesRespondToSelector: selector >> i tng c to bi lp c p ng selector - (id) performSelector: selector >> triu gi chnh sch selector trn i tng.

Constructors - hm khi to: Vn l vi mt lp th hm khi to dng sinh i tng v cng l ch t duy v hm hy v cch thc lu trong b nh ca i tng. V vn hy i tng ta s c mt phn ring v n hon ton khc bit vi vic vit hm hy trong C++ v cc ngn ng khc. Tt nhin khng c g l khng th vit khi bn hiu r v thng tho ngn ng. V hn nhin bn c th qun ht nhng lut v khi to i tng hm to v hm hy ca C++ vi ObC bn hon ton c th t mnh ch bin nhng hm theo thch v cng khng c quy lut g v tn tui ca hm, tuy nhin theo thoi quen truyn thng gip style - code ch nn sng sa nn dng bng cc t nh init hoc tng t... nh ngha hm khi to Fraction.h
Code:

... -(Fraction*) initWithNumerator: (int) n denominator: (int) d; ...

Fraction.m
Code:

... -(Fraction*) initWithNumerator: (int) n denominator: (int) d { self = [super init]; if ( self ) { [self setNumerator: n andDenominator: d]; } return self; } ...

main.m
Code:

#import #import "Fraction.h" int main( int argc, const char *argv[] ) { // create a new instance Fraction *frac = [[Fraction alloc] init]; Fraction *frac2 = [[Fraction alloc] init]; Fraction *frac3 = [[Fraction alloc] initWithNumerator: 3 denominator: 10]; // set the values [frac setNumerator: 1]; [frac setDenominator: 3]; // combined set [frac2 setNumerator: 1 andDenominator: 5];

// print it printf( "The fraction is: " ); [frac print]; printf( "\n" ); printf( "Fraction 2 is: " ); [frac2 print]; printf( "\n" ); printf( "Fraction 3 is: " ); [frac3 print]; printf( "\n" ); // free memory [frac release]; [frac2 release]; [frac3 release]; return 0; } - T kha supper tham chiu ti lp cha. - T kha self tc dng tng ng nh this trong C++. (chnh bn thn ang th hin ca lp - object hin ti) - Kt thc hm khi to (init) s tr v chnh i tng dc to ra thng qua t kha self. - Mc nh trong ObC hm khi to l - (id) init; - Trong ObC hm khi to ch c ngha v mt t duy, n khng c i s c bit ging nh C++. a hnh. c l vi nhng trnh by trn phn no gip bn mng tng ra dc c ch a hnh ca ObC. phn ny ch l vit thm nhm cng c mt s nhng im sau y. 1. Trong ObC khng c t kha virtual v thc s l khng cn thit v n s khng to ra nhng th qu phc tp ging nh C++ v vic ph quyt hm trong ObC l ph quyt trng chn khng lin quan g ti s k tha. nu 2 hm ging ht nhau 2 lp quan h cha con th cng chng sao c. cng cn ni thm l ObC l n k tha. 2. Qu trnh to mi lin h gia th hin ca ObC v phng thc s c gi l thi im run-time. iu ny hon ton c ngha nu bn gi mt phng thc m bn thn i tng khng c cng khng c li g. Li ch xy ra khi li gi dc thc hin. Tuy nhin ban cng dc cung cp nhng c ch kim sot vic ny. y cng l mt c tnh RunTime ca ObC nu bn quan tm c th tm kim thng tin t vic chuyn tip thng ip (forward) ti mt i tng khc. Qun ly b nh. ObC c 2 la chn cho vic qun l b nh. Thng thng b nh dc qun l bi lp trnh vin, ObC c trnh bin dch ch th nh "release", "retain", "autorelease" l nhng ch th h ch lp trnh vin mnh m trong vic qun l b nh. ObC s dng mt tham chiu m d tm ra nhng thay i trn mt i tng. Bin m ny s tng ln mt khi i tng dc cp pht b nh bng phng thc alloc, bin m ny s gim i mt khi i tng dc gii phng bng phng thc dealloc. Nh vy nguyn l cp pht v duy tr b nh ca i tng trong ObC dc s dng thng qua phng thc alloc v dealloc.

Mt khc tin ch khc t kiu d liu nil ni trn vic gii phng b nh. Trong ng cnh mt i tng ca bn l bao gm nhiu nhng i tng khc. nhng i tng khc c th dc gii phng hoc cha. nh th bn s thc hin li gi dealloc trn tp i tng m bn c, nu con th n s thc hin gii phng trong trng hp bng nil cng ok khng vn g (no error) v nil cng c th truyn thng ip. hy xem v d # AddressCard.h
Code:

#import #import @interface AddressCard: NSObject { NSString *first; NSString *last; NSString *email; } -(AddressCard*) initWithFirst: (NSString*) f last: (NSString*) l email: (NSString*) e; -(NSString*) first; -(NSString*) last; -(NSString*) email; -(void) setFirst: (NSString*) f; -(void) setLast: (NSString*) l; -(void) setEmail: (NSString*) e; -(void) setFirst: (NSString*) f last: (NSString*) l email: (NSString*) e; -(void) setFirst: (NSString*) f last: (NSString*) l; -(void) print; @end # AddressCard.m
Code:

#import "AddressCard.h" #import @implementation AddressCard -(AddressCard*) initWithFirst: (NSString*) f last: (NSString*) l email: (NSString*) e { self = [super init]; if ( self ) { [self setFirst: f last: l email: e]; } return self; } -(NSString*) first {

return first; } -(NSString*) last { return last; } -(NSString*) email { return email; } -(void) setFirst: (NSString*) f { [f retain]; [first release]; first = f; } -(void) setLast: (NSString*) l { [l retain]; [last release]; last = l; } -(void) setEmail: (NSString*) e { [e retain]; [email release]; email = e; } -(void) setFirst: (NSString*) f last: (NSString*) l email: (NSString*) e { [self setFirst: f]; [self setLast: l]; [self setEmail: e]; } -(void) setFirst: (NSString*) f last: (NSString*) l { [self setFirst: f]; [self setLast: l]; } -(void) print { printf( "%s %s <%s>", [first cString], [last cString], [email cString] ); } -(void) dealloc { [first release]; [last release]; [email release]; [super dealloc]; } @end

# main.m
Code:

#import "AddressCard.h" #import #import int main( int argc, const char *argv[] ) { NSString *first =[[NSString alloc] initWithCString: "Tom"]; NSString *last = [[NSString alloc] initWithCString: "Jones"]; NSString *email = [[NSString alloc] initWithCString: "tom@jones.com"]; AddressCard *tom = [[AddressCard alloc] initWithFirst: first last: last email: email]; // we're done with the strings, so we must dealloc them [first release]; [last release]; [email release]; // print to show the retain count printf( "Retain count: %i\n", [[tom first] retainCount] ); [tom print]; printf( "\n" ); // free memory [tom release]; return 0; } # output Retain count: 1 Tom Jones
Trch dn:

Mt khc ObC cng cung cp mt c ch thng minh thng thng trong vic bn gi v s dng i tng m khng phi quan tm lo lng n vic cp pht v gii phng b nh l c ch NSAutoreleasePool. dng dc c ch ny bn ch vic nh 2 iu kp on code m bn mun kim sot vo trong gia NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init] v [pool release]. Nguyn l ca ng ch ny cng ging nh li gi hm v th bn hon ton c th s dng lng nhau v s ng m hp l (ging nh th ng v m ca XML ) t nhin ObC s y cc li gi pool sau xung stack v t pool mi trn cng sau nht cc object dc to ra trong lng n vo ci pool va mi to nu song th gii phng ri li y tip thng pool di ln c th... kinh cha . 1.1. Association References S dng tham chiu lin kt gi lp vic b sung cc bin th hin i tng vo mt i tng khc. Vic khi to mt tham chiu lin kt ch yu da trn mt key, ta c th thm nhiu lin kt nu ta mun vi nhiu key khc nhau, s dng hm runtime ca Objective-C l objc_setAssociatedObject

void objc_setAssociatedObject (id object, void *key, id value, objc_AssociationPolicy policy) object: i tng ngun ca lin kt key: kha ca lin kt. Kha ny thng l i tng static. value: gi tr lin kt vi kha cho i tng. a gi tr nil xa mt lin kt tn ti policy: cc policy cho lin kt static char overviewKey; NSArray *array = [[NSArray alloc] initWithObjects:@One, @Two, @Three, nil]; NSString *overview = [[NSString alloc] initWithFormat:@%@, @First three numbers]; objc_setAssociatedObject(array, &overviewKey, overview, OBJC_ASSOCIATION_RETAIN); To lin kt overview vo i tng array, ta truy xut i tng lin kt overview thng qua i tng array v kha NSString *associatedObject = (NSString *)objc_getAssociatedObject(array, &overviewKey); 1.2. Selector Trong Objective-C, khi nim Selector c 2 ngha. N c th c dng n gin l ch n tn ca mt phng thc khi n c s dng trong m ngun mt thng ip gi n mt i tng. Bn cnh n cn ch n mt nh danh duy nht m thay th cho mt tn khi m ngun c bin dch Selector khi c bin dch c kiu l SEL. Tt c cc phng thc c cng tn th c cng selector. Ta c th s dng mt selector triu gi mt phng thc trn mt i tng, iu ny th hin kh cn bn mu thit k target-action trong Cocoa.
Code:

SEL setWidthHeight; setWidthHeight = @selector(setWidth:Height:); Ch th @selector cho php ta tham chiu n mt selector c bin dch hn l tn mt phng thc y . on m trn l mt selector cho phng thc setWidth:Height c assign cho bin SEL l setWidthHeight. trn trng hp ta tham chiu n mt selector thng qua ch th @selector, trong mt s trng hp ta c th chuyn t mt chui k t thnh mt selector trong thi im runtime bng phng thc NSSelectorFromString. setWidthHeight = NSSelectorFromString(aBuffer); V ngc li ta c th ly tn phng thc t mt selector thng qua phng thc NSStringFromSelector.
Code:

NSString *method;

method = NSStringFromSelector(setWidthHeight); Mt selector bin dch ch nh mt tn phng thc ch khng thc thi phng thc. V d, c mt phng thc Display cho mt lp, c nhiu selector ging nhau cho phng thc Display cc lp khc, vi mc ch a hnh v rng buc ng. Nu c mt selector cho mi phng thc thc thi, th mt thng ip s khng khc mt li gi phng thc. Mt phng thc lp v mt phng thc th hin c cng tn c assign bi mt selector. Tuy nhin, bi v 2 phng thc ny phn bit domain (phm vi lp, phm vi i tng ca lp) nn s khng c s nhm ln gia 2 phng thc ny. Vic nh tuyn mt thng ip truy xut vo mt phng thc ch thng qua mt selector duy nht, v vy n i x nh nhau i vi cc phng thc c cng selecor. N pht hin kiu tr v ca phng thc v kiu d liu ca cc tham s thng qua selector. V vy, ngoi tr thng ip truyn vo cc b nhn kiu tnh, cn li vi cc rng buc ng n yu cu tt c cc tn phng thc thc thi phi c cng kiu tr v v c tham s cng kiu. (cc b nhn kiu tnh l ngoi l, trnh bin dch c th bit v cc phng thc thc thi t kiu lp). Mc d nh danh ca phng thc lp v phng thc th hin l cng mt selector, nhng chng c th c kiu tr v v kiu ca cc tham s khc nhau. Ba phng thc performSelector:, performSelector:withObject:, v performSelector:withObject:withObject:, nh ngha trong protocol NSObject ly cc nh danh SEL nh l cc tham s khi to. Tt c cc phng thc ny nh x trc tip vo thng ip phng thc. V d:
Code:

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


Code:

[friend gossipAbout:aNeighbor]; Hoc v d:


Code:

id SEL

helper = getTheReceiver(); request = getTheSelector();

[helper performSelector:request]; Cc phng thc c th bin i ti thi im runtime, nh trn b nhn helper c chn thng qua phng thc getTheReceiver v b nhn ny c yu cu thc hin phng thc request thng qua phng thc getTheSelector ti thi im runtime. Lu , khi mt b nhn buc phi thc hin mt phng thc m khng thuc phm vi ca mnh thng qua selector th ng nhin s xut hin li. V nhng cng vic ny thc thi thi im runtime nn hin nhin li s ch xut hin ti thi im chng trnh c thc thi.

1.3. X l ngoi l
Code:

@try { } @catch (CustomException *ce) { } @catch (NSException *ne) { // 2 // 1

// Perform processing necessary at this level. } @catch (id ue) { } @finally { // 3 or not.

// Perform processing necessary whether an exception occurred } Bt cc kiu ngoi l c th nht Bt cc kiu ngoi l chung 1.4. Qun l b nh 1.4.1. Cc nguyn tc qun l b nh Nguyn tc c bn

Khi bn nm quyn s hu mt i tng, khi to i tng bng cc phng thc m trong tn bt u vi vi alloc hoc new hoc copy (v d, alloc, newObject hoc mutableCopy) hoc gi mt thng ip retain, bn phi c trch nhim gii phng quyn s hu i tng bng cch s dng release hoc autorelease. Bt k khi no bn nhn c mt i tng (khng phi t mnh khi to), bn khng c release n. Cc nguyn tc khc Khi bn cn lu tr mt i tng c nhn nh mt property trong mt bin th hin, bn phi retain hoc copy n. (iu ny khng ng cho cho tham kho yu, nhng y l in hnh him). Mt i tng c nhn thng m bo vn c hiu lc trong phng thc m n c

nhn (ngoi tr trong cc ng a lung v vi trng hp Distributes Objects). Phng thc c th tr v an ton i tng m n c triu gi. S dng retain trong vic kt hp vi release hoc autorelease khi cn thit bo v mt i tng khi hiu lc ca cc thng ip khng hp l bn ngoi. autorelease c ngha l gi mt thng ip release sau 1.4.2. Vn khi khi to i tng Xt on code khi to i tng sau
Code:

TestClass *ptr = [TestClass alloc]; [ptr init]; // Do something with the object if (ptr) Thot nhn qua c v v hi, phng thc alloc khi to mt vng nh cho i tng ptr, sau gi thng ip gi phng thc init cho i tng ptr, li c th xy ra y. Gi s dng lnh dng lnh [ptr init], phng thc init c li xy ra v tr v nil, tip theo dng lnh if, lc ny ptr vn khc nil mc d phng thc init tr v nil (nhng n khng c gn cho ptr), dn ti ngha ca phng thc to thc s khng cn na. Khi , on code sau s gii quyt c kh nng li trn
Code:

TestClass *ptr = [[TestClass alloc] init]; // Do something with the object if (ptr) Gi s init c li v tr v nil th ptr vn s c gn l nil, do dng lnh if s thc hin ng ngha ca n. ngha t v d ny l, ta lun lun phi tr v nil trong phng thc init nu c li khi to xy ra v lu phi kt hp 2 li gi phng thc alloc v init. 1.4.3. Release Nu bn khi to mt i tng s dng cch th cng alloc, bn cn phi release i tng sau . Bn khng nn thc hin release th cng mt i tng autorealse bi v ng dng c th s b crash nu bn lm iu .
Code:

// string1 will be released automatically NSString* string1 = [NSString string]; // must release this when done NSString* string2 = [[NSString alloc] init]; ..

[string2 release]; 1.4.4. Retain Trong Objective-C, mi i tng c mt b m c s dng kim sot tt c cc tham chiu bi i tng hoc n c. bit c gi tr ca b m ny ta s dng thuc tnh retainCount [object retainCount]. Phng thc alloc, new, copy v retain u tng b m ny ln 1 v phng thc release gim b m ny i 1, khi b m c gi tr bng 0 th phng thc dealloc ca i tng s c gi. Bt c khi no mt i tng c nhu cu c s dng bi mt i tng khc n phi retain tng b m retainCount ln 1, v khi n khng cn s dng na th phi release gim b m retainCount i 1. Khi b m c gi tr bng 0 c ngha l n khng cn nhu cu s dng na, n s t hy bng phng thc dealloc. 1.4.5. Dealloc Phng thc dealloc c gi khi i tng ang c remove khi b nh. N thng c s dng nht khi gii phng tt c cc tham chiu ca cc bin th hin con ca i tng khi b nh. Hay ni cch khc, mt lp nu c cc bin th hin l cc i tng th trong phng thc dealloc ca lp phi thc hin gii phng cc bin th hin ny.
Code:

- (void)dealloc { [childVar1 release]; [childVar2 release]; [super dealloc]; } Phng thc [super dealloc] c s dng thng bo cho lp cha thc hin vic dn dp (y l phng thc c nh ngha trong NSObject), nu khng gi phng thc ny, c th i tng s khng c remove khi b nh, s gy nn tnh trng chim b nh.
Code:

#import <Foundation/Foundation.h> #import Address.h @interface Person : NSObject { Address* address; } -(Person*) constructor: (Address*) add; -(void) show; @end

Code:

#import Person.h @implementation Person -(Person*) constructor: (Address*) add{ self = [super init]; if(self){ address = add; } return self; } -(void) show{ printf(Person: \n); printf( );

[address show]; } -(void) dealloc{ printf(Dealloc method of Person\n); [address release]; [super dealloc]; } @end
Code:

#import <Foundation/Foundation.h> #import Person.h #import Name.h @interface VNPerson : Person { Name* name; } -(VNPerson*) constructor: (Address*) add : (int) idn;

@end
Code:

#import VNPerson.h #import Name.h @implementation VNPerson -(VNPerson*) constructor: (Address*) add : (int) idn{ self = [super constructor: add]; if(self){ name = [[Name alloc] constructor: idn]; } return self; } -(void) show{ [super show]; printf( );

[name show]; } -(void) dealloc{ printf(Dealloc method of VNPerson\n); [name release]; [super dealloc];// Mc ch gii phng bin th hin address trong lp cha } @end
Code:

#import Address.h #import VietnamAddress.h #import Person.h #import VNPerson.h int main(int argc, char *argv[]) {

Address *address = [[Address alloc] constructor: 01 : 02]; [address show]; VietnamAddress *vnaddress = [[VietnamAddress alloc] constructor: 03 : 04]; [vnaddress show]; [vnaddress changeAddress: 05]; Person *person = [[VNPerson alloc] constructor: address : 1915]; [person show]; [address release]; [vnaddress release]; [person release]; return 1; } Lu : Phng thc dealloc s khng c gi trong trng hp b dn rc c bt. 1.4.6. Tham chiu yu Retain mt i tng to ra mt tham chiu mnh n i tng . Mt i tng khng th dealloc cho ti khi tt c cc tham chiu mng c gii phng ht. Trong mt s trng hp, ta c th mun c mt tham chiu n i tng m khng cn tr vic i tng t gii phng chnh n, lc ny ta c th thit lp mt tham chiu yu n i tng. Mt tham chiu yu c to ra bng cch cha mt con tr tr n mt i tng m khng retain i tng . Tham chiu yu rt cn thit trong vic thit lp cc tham chiu vng. V d, i tng A v i tng B cn trao i thng tin vi nhau nn mi i tng cn mt tham chiu n i tng kia (v nh mi quan h gia 2 i tng cha con), nu nh chng ta retain i tng kia khi thit lp tham chiu th mi i tng ch c dealloc khi no kt ni ny t, tuy nhin kt ni ny ch t khi c mt i tng c dealloc m thi. Trong trng hp ny ta thy c li ch ca tham chiu yu. Chng ta phi tht cn thn khi truyn thng ip trong tham chiu yu, trong trng hp i tng nhn thng ip dealloc th ng dng c th s b crash. ng thi, trong mi quan h tham chiu yu, i tng c tham chiu n phi c trch nhim bo cho i tng kia bit khi n thc hin dealloc, v d gi mt thng ip setDelegate: vi tham s nil cho i tng kia chng hn, trong trng hp i tng dealloc l mt Delegate ca i tng nhn thng ip.

Thc hnh Objective C vi GNUStep trn ubuntu


u tin bn ci t cc gi sau lp trnh:
Trch dn:

sudo apt-get sudo apt-get sudo apt-get sudo apt-get sudo apt-get g lnh
Trch dn:

-y install build-essential -y install gnustep install gobjc install gnustep-make install libgnustep-base-dev

sudo gedit /etc/profile thm vo cui file dng sau


Trch dn:

export GNUSTEP_MAKEFILES=/usr/share/GNUstep/Makefiles sau khi ng li my ubuntu nhn bin mi trng 1) bi thc hnh lp trnh C thun vi trnh bin dch objective C GNUstep to file main.c
Code:

#include <stdio.h> int main(void) { printf("Hello World\n"); } to GNUmakefile vi ni dung nh sau:


Code:

include $(GNUSTEP_MAKEFILES)/common.make CTOOL_NAME = HelloWorld HelloWorld_HEADERS = HelloWorld_C_FILES = main.c HelloWorld_RESOURCE_FILES = include $(GNUSTEP_MAKEFILES)/ctool.make t vo cng th mc v g lnh make g lnh
Trch dn:

./shared_obj/HelloWorld in ra kt qu mn hnh Bi 2) vit 1 chng trnh thun C s dng C posix trn MACOS main.c
Code:

#include <stdio.h> #include <stdlib.h> #include <pthread.h> void *Day_la_Thread_Ma_Ban_CanDung( void *ptr ) { char *message; message = (char *) ptr; printf("%s \n", message); } int main() { pthread_t thread1, thread2; char *message1 = "Sonnh89: Day la Thread 1"; char *message2 = "Sonnh89: Day la Thread 2"; int iret1, iret2; iret1 = pthread_create( &thread1, NULL, Day_la_Thread_Ma_Ban_CanDung, (void*) message1); iret2 = pthread_create( &thread2, NULL, Day_la_Thread_Ma_Ban_CanDung, (void*) message2); pthread_join( thread1, NULL);//day la ham wait cho thread thuc hien xong moi chay tiep pthread_join( thread2, NULL); printf("GIa Tri Tra ve: %d\n",iret1); printf("GIa Tri Tra ve: %d\n",iret2); return 0; } gnumakefile
Trch dn:

include $(GNUSTEP_MAKEFILES)/common.make CTOOL_NAME = HelloWorld HelloWorld_HEADERS = HelloWorld_C_FILES = main.c HelloWorld_RESOURCE_FILES = ADDITIONAL_TOOL_LIBS += -pthread include $(GNUSTEP_MAKEFILES)/ctool.make Bi 3) Vit chng trnh s dng Objective C v C thun khai bo 1 kiu id c dng Greeter k tha t lp Object main.m
Code:

#include <objc/Object.h> @interface Greeter:Object { } - (void)greet;

@end #include <stdio.h> @implementation Greeter//thuc hien code - (void)greet { printf("Hello, World!\n"); } @end #include <stdlib.h> int main(void) { id myGreeter;//khai bao bien ID greeter myGreeter=[Greeter new];//cap phat greeter [myGreeter greet];//goi ham greet [myGreeter free];//giai phong Greeter return EXIT_SUCCESS; } i vi C thun v objective C th th vin makefile: include $(GNUSTEP_MAKEFILES)/common.make ging ht nhau, u cn phi thm vo i tn CTOOL_NAME = HelloWorld thnh tn OBJC_PROGRAM_NAME tng ng vi kiu objective C GNUmakefile:
Code:

include $(GNUSTEP_MAKEFILES)/common.make OBJC_PROGRAM_NAME = HelloWorld HelloWorld_HEADERS = HelloWorld_OBJC_FILES = main.m HelloWorld_RESOURCE_FILES = include $(GNUSTEP_MAKEFILES)/objc.make

Bi 4
objective C v C cng c s khc nhau ging nh ca C++ v C t kha +new v +alloc/-init u cng l cp pht ng, n tng t vi new v malloc ca C++ v C, thng thng, nu khg c g c bit th bn nn dng new thay v dng init/alloc Headers lp trnh vi ng php ca ngn ng C, bn phi include th vin
Trch dn:

#include <Foundation/NSArray.h> ngoi ra, bn cng c th s dng t kha thun Objective C l import
Trch dn:

#import <Foundation/NSArray.h> trnh vic quy trong vic include cc th vin, bn s dng #ifdef
Trch dn:

#ifndef HAVE_NSARRAY_H #define HAVE_NSARRAY_H #include <Foundation/NSArray.h> #endif

[Objective C] Hng dn tch hp OpenGL ES Template vo Xcode


OpenGL l g ? c pht trin u tin bi Silicon Graphic, Inc., l mt giao din phn phn mm hng th tc theo chun cng nghip h tr ha 3 chiu. Cung cp khong 120 tc v v cc primitive trong nhiu mode khc nhau. Vi OpenGL, bn c th to ra nh 3 chiu c tnh v ng vi cht lng cao. L mt giao din phn mm c lp vi phn cng (hardware independent software interface) h tr cho lp trnh ha. lm c iu ny, OpenGL khng thc hin cc tc v thuc v h iu hnh cng nh khng nhn d liu nhp ca ngi dng (ngi dng giao tip vi OpenGL thng qua OpenGL API). N l lp trung gian gia ngi dng v phn cng. Ngha l n giao tip trc tip vi driver ca thit b ha. GLUT (pronounced like the glut in gluttony) is the OpenGL Utility Toolkit, a window system independent toolkit for writing OpenGL programs. It implements a simple windowing application programming interface (API) for OpenGL. GLUT makes it considerably easier to learn about and explore OpenGL programming. GLUT provides a portable API so you can write a single OpenGL program that works across all PC and workstation OS platforms. xy dng mt ng dng ha 3D th i hi bn phi c mt s kin thc nht nh v hnh hc khng gian, thm vo l cc php ton trn ma trn. Trong OpenGL ES, mt im trong khng gian ngi ta dng thut ng vertex. V hnh phc tp nht m bn c th v l mt tam gic. Mt vertex c th thuc vo cc tam gic khc nhau. Bn to ra cc i tng phc tp khc bng cch v cc tam gic ny theo mt th t no chng ghp li vi nhau to nn mt hnh th hon chnh. Cc i tng ba chiu phi c phn gii thnh tng th vi cc mnh tam gic c th v ra mn hnh. Mi im ring bit trong khng gian c mu ring ca n. Mu ca mt vng tam gic ph thuc vo mu ca 3 im to nn n. Bn c th quyt nh phm vi ca h trc ta . Theo quy c trc Z c chiu dng hng v pha bn, trc X c chiu dng i v pha tay phi v trc Y c chiu dng hng ln trn. Cc php bin i c s c sn gm c php quay v php tnh tin. Cc php bin i ny c thc thi trc khi bn v cc im ca mnh ln mn hnh. Ti mi thi im bn c mt ma trn trng thi hin thi. Khi ta thc thi mt php bin i tc l ta nhn ma trn trng thi hin thi vi ma trn bin i v lu kt qu ma trn trng thi hin thi. Khi v th cc ta im v s c bin i thng qua ma trn trng

thi hin thi. V s c mt ngn xp lu gi cc ma trn hin thi lu li cc trng thi tm thi, iu ny cho php bn c th quay v ma trn n v ban u. Mt khi nim khc na l cc Texture, l nhng bc nh m c th c p vo mt b mt hnh hc no , OpenGL ES s un cong hoc lm gp chng li cho thch hp vi b mt . iu ny cng tng t nh vic bn mc mt b qun o vy, c th bn l b mt cn qun o chnh l cc texture. Vi texture bn d dng to ra cc b mt ging nh mnh mong mun, tuy nhin n s chim nhiu b nh hn so vi vic dng mu sc n thun. V b mt hin th ca mn hnh l mt phng 2 chiu, do hin th cc i tng 3 chiu bn phi s dng n cc php chiu. C 2 loi php chiu c bn, l php chiu trc giao v php chiu phi cnh. Php chiu trc giao cho kt qu nhanh hn v chi ph tnh ton t nhng li khng m t i tng mt cch "chn thc", ngc li php chiu phi cnh cho ta mt ci nhn ging tht hn nhng chi ph tnh ton nhiu hn. Ty vo mc ch ng dng m bn c th s dng mt trong hai php chiu ny. OpenGL ES ch h tr texture 2D, nhng bn vn c th s dng nhiu texture mt ln, c th dng thm cc hiu ng nh l sng m, phn chiu, trong sut,... Bn ch rng, mi phin bn OpenGL ES tng ng vi mt phin bn OpenGL. V d, OpenGL ES 1.0 l tp con ca OpenGL 1.3, OpenGL ES 1.1 l tp con ca OpenGL 1.5,... y l template danh cho Xcode http://innerloop.biz/code/Empty%20Op...pplication.zip tch hp vo Xcode bn gii nn ra v copy vo ng dn /Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Project Templates/Application/Window-Based Application v by gi, sau khi khi ng Xcode, bn c s 1 template c tn l: Empty OpenGL Application

Sau y mnh s gii thiu 1 chng trnh OpenGL ES n gin c convert t lession 2 ni ting ca Nehe NeHe_Lesson_02AppDelegate.h
PHP Code:

// // // // // // //

NeHe_Lesson_02AppDelegate.h NeHe Lesson 02 Created by Jeff LaMarche on 12/11/08. Copyright Jeff LaMarche Consulting 2008. All rights reserved.

#import "GLView.h" @interface NeHe_Lesson_02AppDelegate : NSObject <UIApplicationDelegate, GLTri angleViewDelegate> { UIWindow* window; } @property (nonatomic, retain) IBOutlet UIWindow *window; @end
PHP Code:

// // // // // // // // // // // // //

NeHe_Lesson_02AppDelegate.m NeHe Lesson 02 Created by Jeff LaMarche on 12/11/08. Copyright Jeff LaMarche Consulting 2008. All rights reserved. This is a port of the code from http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=02 Because OpenGL ES doesn't support glBegin or glEnd, this code uses vertex arrays, which the NeHe tutorials don't cover until much later, but we have no choice.

#import "NeHe_Lesson_02AppDelegate.h" #define DEGREES_TO_RADIANS(__ANGLE__) ((__ANGLE__) / 180.0 * M_PI) #define kRenderingFrequency 60.0 @implementation NeHe_Lesson_02AppDelegate @synthesize window; - (void)drawView:(GLView*)view; { const GLfloat triVertices[] = { 0.0f, 1.0f, 0.0f, -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f }; const GLfloat quadVertices[] = { -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f, -1.0f, -1.0f, 0.0f }; glClear(GL_COLOR_BUFFER_BIT); glLoadIdentity(); glTranslatef(-2.0f,1.0f,-6.0f); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, triVertices); glDrawArrays(GL_TRIANGLE_STRIP, 0, 3); glTranslatef(4.0f, 0.0f, 0.0f); glVertexPointer(3, GL_FLOAT, 0, quadVertices);

glDrawArrays(GL_TRIANGLE_FAN, 0, 4); } -(void)setupView:(GLView*)view { const GLfloat zNear = 0.1, zFar = 1000.0, fieldOfView = 60.0; GLfloat size; glMatrixMode(GL_PROJECTION); size = zNear * tanf(DEGREES_TO_RADIANS(fieldOfView) / 2.0); CGRect rect = view.bounds; glFrustumf(-size, size, size / (rect.size.width / rect.size.height), size / (rect.size.width / rect.size.height), zNear, zFar); glViewport(0, 0, rect.size.width, rect.size.height); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); } - (void)applicationDidFinishLaunching:(UIApplication*)application { CGRect rect = [[UIScreen mainScreen] bounds]; window = [[UIWindow alloc] initWithFrame:rect]; GLView *glView = [[GLView alloc] initWithFrame:rect]; [window addSubview:glView]; glView.delegate = self; glView.animationInterval = 1.0 / kRenderingFrequency; [glView startAnimation]; [glView release]; [window makeKeyAndVisible]; } - (void)dealloc { [window release]; [super dealloc]; } @end
PHP Code:

// // GLView.h // NeHe Lesson 02 //Lp GLivew c sinh ra k tha t lp ca UItoolKit kt ni gia OpenGL v UIToolkit // #import <UIKit/UIKit.h> #import <OpenGLES/EAGL.h>

#import <OpenGLES/ES1/gl.h> #import <OpenGLES/ES1/glext.h> @protocol GLTriangleViewDelegate; @interface GLView : UIView//k tha lp UIView hin th giao din OpenGL { @private // The pixel dimensions of the backbuffer GLint backingWidth; GLint backingHeight; EAGLContext *context; GLuint viewRenderbuffer, viewFramebuffer; GLuint depthRenderbuffer; NSTimer *animationTimer; NSTimeInterval animationInterval; id<GLTriangleViewDelegate> delegate; BOOL delegateSetup; } @property(nonatomic, assign) id<GLTriangleViewDelegate> delegate; -(void)startAnimation; -(void)stopAnimation; -(void)drawView; @property NSTimeInterval animationInterval; @end @protocol GLTriangleViewDelegate<NSObject> @required -(void)drawView:(GLView*)view; @optional -(void)setupView:(GLView*)view; @end

PHP Code:

// // // // // // //

GLView.m NeHe Lesson 02 Created by Jeff LaMarche on 12/11/08. Copyright Jeff LaMarche Consulting 2008. All rights reserved.

#import <QuartzCore/QuartzCore.h> #import <OpenGLES/EAGLDrawable.h> #import "GLView.h" @interface GLView (private)

- (id)initGLES; - (BOOL)createFramebuffer; - (void)destroyFramebuffer; @end @implementation GLView @synthesize animationInterval; + (Class) layerClass { return [CAEAGLLayer class]; } -(id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if(self != nil) { self = [self initGLES]; } return self; } - (id)initWithCoder:(NSCoder*)coder { if((self = [super initWithCoder:coder])) { self = [self initGLES]; } return self; } -(id)initGLES { CAEAGLLayer *eaglLayer = (CAEAGLLayer*) self.layer; // Configure it so that it is opaque, does not retain the contents of the backbuffer when displayed, and uses RGBA8888 color. eaglLayer.opaque = YES; eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys : [NSNumber numberWithBool:FALSE], kEAG LDrawablePropertyRetainedBacking, kEAGLColorFormatRGBA8, kEAGLDrawableP ropertyColorFormat, nil]; // Create our EAGLContext, and if successful make it current and create o ur framebuffer. context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1]; if(!context || ![EAGLContext setCurrentContext:context] || ![self createF ramebuffer]) { [self release]; return nil; }

// Default the animation interval to 1/60th of a second. animationInterval = 1.0 / 60.0; return self; } -(id<GLTriangleViewDelegate>)delegate { return delegate; } // Update the delegate, and if it needs a setupView: call, set our internal flag so that it will be called. -(void)setDelegate:(id<GLTriangleViewDelegate>)d { delegate = d; delegateSetup = ![delegate respondsToSelector:@selector(setupView:)]; } // If our view is resized, we'll be asked to layout subviews. // This is the perfect opportunity to also update the framebuffer so that it is // the same size as our display area. -(void)layoutSubviews { [EAGLContext setCurrentContext:context]; [self destroyFramebuffer]; [self createFramebuffer]; [self drawView]; } - (BOOL)createFramebuffer { // Generate IDs for a framebuffer object and a color renderbuffer glGenFramebuffersOES(1, &viewFramebuffer); glGenRenderbuffersOES(1, &viewRenderbuffer); glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer); glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer); // This call associates the storage for the current render buffer with th e EAGLDrawable (our CAEAGLLayer) // allowing us to draw into a buffer that will later be rendered to scree n whereever the layer is (which corresponds with our view). [context renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:(id<EAGLDra wable>)self.layer]; glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES , GL_RENDERBUFFER_OES, viewRenderbuffer); glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDT H_OES, &backingWidth); glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIG HT_OES, &backingHeight); // For this sample, we also need a depth buffer, so we'll create and atta ch one via another renderbuffer. glGenRenderbuffersOES(1, &depthRenderbuffer); glBindRenderbufferOES(GL_RENDERBUFFER_OES, depthRenderbuffer);

glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, b ackingWidth, backingHeight); glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthRenderbuffer); if(glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMP LETE_OES) { NSLog(@"failed to make complete framebuffer object %x", glCheckFrameb ufferStatusOES(GL_FRAMEBUFFER_OES)); return NO; } return YES; } // Clean up any buffers we have allocated. - (void)destroyFramebuffer { glDeleteFramebuffersOES(1, &viewFramebuffer); viewFramebuffer = 0; glDeleteRenderbuffersOES(1, &viewRenderbuffer); viewRenderbuffer = 0; if(depthRenderbuffer) { glDeleteRenderbuffersOES(1, &depthRenderbuffer); depthRenderbuffer = 0; } } - (void)startAnimation { animationTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterva l target:self selector:@selector(drawView) userInfo:nil repeats:YES]; } - (void)stopAnimation { [animationTimer invalidate]; animationTimer = nil; } - (void)setAnimationInterval:(NSTimeInterval)interval { animationInterval = interval; if(animationTimer) { [self stopAnimation]; [self startAnimation]; } } // Updates the OpenGL view when the timer fires - (void)drawView {

// Make sure that you are drawing to the current context [EAGLContext setCurrentContext:context]; // If our drawing delegate needs to have the view setup, then call setupView: and flag that it won't need to be called again. if(!delegateSetup) { [delegate setupView:self]; delegateSetup = YES; } glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer); [delegate drawView:self]; glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer); [context presentRenderbuffer:GL_RENDERBUFFER_OES]; GLenum err = glGetError(); if(err) NSLog(@"%x error", err); } // Stop animating and release resources when they are no longer needed. - (void)dealloc { [self stopAnimation]; if([EAGLContext currentContext] == context) { [EAGLContext setCurrentContext:nil]; } [context release]; context = nil; [super dealloc]; } @end Di y, ti s hng dn cc bn cch porting 1 source code OpenGL sang OpenGL ES Bn nn c k bi hng dn ca nehe,nhng bn cng nn ch l k thut v ca nehe s dung glBegin v GlEnd l khng c h tr trong OpenGL ES Trong code ca Nehe
PHP Code:

glBegin(GL_TRIANGLES); glVertex3f( 0.0f, 1.0f, glVertex3f(-1.0f,-1.0f, glVertex3f( 1.0f,-1.0f, glEnd(); // Finished


Trch dn:

// Drawing Using Triangles 0.0f); // Top 0.0f); // Bottom Left 0.0f); // Bottom Right Drawing The Triangle

The call to glBegin() tells OpenGL that the code that follows is going to define points (or vertices) in virtual space. Then the three calls to glVertex3f define the vertices using cartesian coordinates (x, y, z). Because GL_TRIANGLES was specified in glBegin(). OpenGL

will draw and fill the triangle defined by the three vertices specified before the call to glEnd() Trn Iphone, thay th vo vic , chng ta v bng cch t chng chng thnh 1 mng c 3 phn t, ng vi 3 im
PHP Code:

const GLfloat triVertices[] = { 0.0f, 1.0f, 0.0f, -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f }; sau , nh dng cch v, chng ta gi hm sau
Code:

glVertexPointer(3, GL_FLOAT, 0, triVertices); Hm ny s nh ngha bin triVerrtices l 1 mng c kiu chp, ngha l cc phn t ca n s c dng (x, y, z), s l cc nh ca 1 hnh 2D ( v d nh tam gic, hnh vung... ), tham s GL_FLOAT ngha l chng ta thng bo rng cc d lieeuj trong s c kiu GLfloat, tham s th 3 khng s dng, n s l 0 v cui cng, v n ln mn hnh, chng ta gi hm glDrawArrays(GL_TRIANGLES, 0, 3); Cc Thumbnail nh km

[Objective C] Hng dn vit Image view n gin


Mt tutorial n gin cho ngi mi lm quen vi Xcode-Objective C hin th 1 bc nh trong Iphone c lp UIImageview, ta ch cn gi hm setimage hoc gn thuc tnh image cho n l c di y l 1 on code n gin:
Code:

(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfac eOrientation { NSURL * imageURL = [NSURL URLWithString:@"http://dantri4.vcmedia.vn/xAMQAUs9LhwrT16Af2k/Image/2011/06/N N21811_557b3.jpg"];//ly ng dn URL l link ca trang nh v NSData * imageData = [NSData dataWithContentsOfURL:imageURL];//convert n sang kiu NSData cui cng s a sang kiu UIImage UIImage * image = [UIImage imageWithData:imageData]; imgViewer.image = image; // Return YES for supported orientations return (interfaceOrientation == UIInterfaceOrientationPortrait);

You might also like