Allocation and release of object within a method in Objective-C? -
i made move objective-c. doing exercises kochan's programming in objective-c 2.0. on particular exercise, asked modify print method , optional argument:
-(void)print{ nslog(@" %i/%i ", numerator, denominator); }
for created print
method take bool
argument , modified existing print method follows:
-(void)print{ [self printreduced:false]; } -(void)printreduced:(bool)r{ if(r){ [self reduce]; } nslog(@" %i/%i ", numerator, denominator); }
but last part of exercise, supposed use bool
determine if fraction should reduced or not (no problem testing flag), when reduced not supposed modify original object. allocated new fraction object inside printreduced
method , released before end of method too:
-(void)printreduced:(bool)r{ fraction *printingfraction = [[fraction alloc] init]; [printingfraction setto:numerator over:denominator]; if(r){ [printingfraction reduce]; } nslog(@" %i/%i ",[printingfraction numerator], [printingfraction denominator]); [printingfraction release]; }
my question is: right create , release objects whithin given method way? seems work fine without modifying original fraction, right approach?
this correct. whenever 'alloc' object, own it. before goes out of scope (the end of method in case), must relinquish ownership, release in case.
Comments
Post a Comment