# Import "Fraction.h"
int main (int argc, const 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];
NSLog (@ "En ter 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];
sum = sum2;
pow2 * = 2;
}
NSLog (@ "After% i iterations, the sum is% g", n, [sum convertToNum]);
[AFraction release];
[Sum release];
[Pool drain];
return 0;
}
Such operating normally, but I do not understand why sum2 not release. Behind plus a release would be wrong ~
Reply:
iOS default rule is that the memory allocation whom who release, sum2 you did not allocate memory, there is no need to release. If you add a memory allocation function, then they need to add a function to release. If the returned object is the need to release, add function calls autorelease, is not released immediately, but when you are finished using the message loop when the current program ends real release.
Reply:
ls that's good. Memory management is one of the principles to be followed is the "Who assigned who released"
Where [sum add: aFraction] add to the sum of sending a message, and this internal add function calls autorelease, managed by the NSAutoreleasePool not released immediately, but when you are finished using the messaging program in the current cycle At the end of a real release.
Reply:
Note: When using the automatic release of the release pool to release the object is zero, or can not afford to be released
Reply:
sum2 itself does not have a retain property, sum2 = [sum add: aFraction]; This does not make retainCount plus 1. Since the sum and sum2 point to the same block of memory, when executing [sum release]; later, retainCount reaches 0; then memory has been released. There is a problem landlord code is [sum release]; number of execution times and retain, alloc copy of the class implementation does not match, if we adopt the way of debugging code landlord will anomalies.
No comments:
Post a Comment