Allocation and release of object within a method in Objective-C?
I just recently made the move to Objective-C. 开发者_如何学PythonI am doing some exercises from Kochan's Programming in Objective-C 2.0. On this particular exercise, I am asked to modify the print method with and optional argument:
-(void)print{
NSLog(@" %i/%i ", numerator, denominator);
}
For this I simply created another print
method that would take a BOOL
argument and modified the existing print method as follows:
-(void)print{
[self printReduced:FALSE];
}
-(void)printReduced:(BOOL)r{
if(r){
[self reduce];
}
NSLog(@" %i/%i ", numerator, denominator);
}
But for the last part of the exercise, I am supposed to use that BOOL
to determine if the Fraction should be reduced or not (no problem testing the flag), but when reduced I am not supposed to modify the original object. For this I allocated a new Fraction object inside the printReduced
method and released it before the end of the 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: Is it right to create and release objects whithin a given method this way? This seems to do the work just fine without modifying the original Fraction, but is this the right approach?
This is correct. Whenever you 'alloc' an object, you own it. Before it goes out of scope (the end of the method in this case), you must relinquish ownership, a release in this case.
Is the last line meant to be [printingFraction release];
? If you change it to that, your solution is correct. When you alloc
an object you have to release
it at some point.
精彩评论