Hi guys,
I'm relearning Objective-C using Steve Kochans book and I don't understand why the one program doesn't generate an error. I assure you the classes that are referenced are correct but check out the main function:
I highlighted the section I was confused on. Notice how I release sum, then the line right after I assign sum a value! How does this not result in an access error?
Sum is not being declared within the loop so once it is released it should be gone correct? If I try and release and reassign sum outside of the loop in the same way that is done within the loop then it does generate an error. How come the sum inside the loop isn't doing the same?
The only conclusion I can come to is it is scope related. Can someone please clarify this for me?
I'm relearning Objective-C using Steve Kochans book and I don't understand why the one program doesn't generate an error. I assure you the classes that are referenced are correct but check out the main function:
Code:
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];
[B][sum release];[/B] [B][COLOR="Red"]//Why does this work? Is it scope related?[/COLOR][/B]
[B]sum = sum2;[/B] [B][COLOR="red"]//Wait! sum was just released![/COLOR][/B]
pow2 *= 2;
}
NSLog(@"After %i iterations, the sum is %g", n, [sum convertToNum]);
[aFraction release];
[sum release];
[pool drain];
return 0;
}
I highlighted the section I was confused on. Notice how I release sum, then the line right after I assign sum a value! How does this not result in an access error?
Sum is not being declared within the loop so once it is released it should be gone correct? If I try and release and reassign sum outside of the loop in the same way that is done within the loop then it does generate an error. How come the sum inside the loop isn't doing the same?
The only conclusion I can come to is it is scope related. Can someone please clarify this for me?