refer to page 163 of Addison Wesley - Programming.in.ObjectiveC.2.0.2nd (2009)
-(Fraction *) add: (Fraction *) f
{
// To add two fractions:
// a/b + c/d = ((a*d) + (b*c)) / (b * d)
// result will store the result of the addition
Fraction *result = [[Fraction alloc] init];
int resultNum, resultDenom;
resultNum = numerator * f.denominator +
denominator * f.numerator;
resultDenom = denominator * f.denominator;
[result setTo: resultNum over: resultDenom];
[result reduce];
return result;
}
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Fraction *aFraction = [[Fraction alloc] init];
Fraction *bFraction = [[Fraction alloc] init];
Fraction *resultFraction;
[aFraction setTo: 1 over: 4]; // set 1st fraction to 1/4
[bFraction setTo: 1 over: 2]; // set 2nd fraction to 1/2
[aFraction print];
NSLog (@ ” + ” );
[bFraction print];
NSLog (@ ” = ” );
resultFaction = [aFraction add: bFraction]; // <== 創建出resultFraction 並回傳
[resultFraction print];
// This time give the result directly to print
// memory leakage here!
[[aFraction add: bFraction] print]; // 創建出來給print 用的result instance 似乎沒有release
[aFraction release];
[bFraction release];
[resultFraction release]; // <== 最後要記得 release 在add 上所創出來的 resultFraction instance
[pool drain];
return 0;
}
另外一個例子來說明如何解決
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Fraction *aFraction = [[Fraction alloc] init];
Fraction *sum = [[Fraction alloc] init], *sum2;
int i, n, pow2;
[sum setTo: 0 over: 1]; // set 1st fraction to 0
NSLog (@ ” Enter your value for n: ” );
scanf ( “ %i ” , &n);
pow2 = 2;
for (i = 1; i <= n; ++i) {
[aFraction setTo: 1 over: pow2];
sum2 = [sum add: aFraction];
[sum release]; // release previous sum, 先釋放之前的
sum = sum2; //然後指標指向現在創立的
pow2 *= 2;
}
NSLog (@ ” After %i iterations, the sum is %g ” , n, [sum convertToNum]);
[aFraction release];
[sum release];
[pool drain];
return 0;
}
沒有留言:
張貼留言