3

here is code

@interface Test : NSObject {
    int val;
}

-(int) GetOne;
@end

@implementation Test
-(int) GetOne {
    return 1;
} 
@end

and use Test class like this

Test * a = [Test new];
Test * __weak b = a;

[b GetOne];
a = nil;

printf("a=%p, b=%p\n", a, b);

the result is b is not 0. why does this happen?

zno
  • 33
  • 3
  • maybe it lives in the autorelease pool – Bryan Chen Jun 28 '13 at 01:50
  • if I remove "[b GetOne];", then the result is b is 0. "GetOne function call" push b to the autorelease pool? – zno Jun 28 '13 at 01:53
  • You should format your question to be more readable – mor Jun 28 '13 at 02:02
  • 1
    thats very likely. because you don't want b deallocated while `[b GetOne]` is executing. try `@autoreleasepool{[b GetOne];}` – Bryan Chen Jun 28 '13 at 02:08
  • I swear I saw almost this exact question yesterday – Kevin Jun 28 '13 at 02:46
  • Not the one from yesterday, but: [strong and weak for local variable, I dont understand](http://stackoverflow.com/questions/10922888/strong-and-weak-for-local-variable-i-dont-understand) – Kevin Jun 28 '13 at 03:07

2 Answers2

3

ARC will generate a jungle of memory management calls and then optimize away what it determines aren't needed. It's a very different process from the manual memory management of old. I make no claims about understanding how the compiler works in that regard, and that's the beauty of it; you don't have to understand.

Think of ARC as a magic black box that makes one promise: if you follow the rules, it will automatically clean up after you eventually. It may not be at the very earliest moment possible, but it will happen.

I've assumed you're using LLVM 4.2 (ships with Xcode 4.6), and I tested it out. The object does indeed end up in an autorelease pool. This is an example of a case where ARC could do better, because the autorelease isn't actually needed.

Following that thought, I also tried it on the LLVM 5.0 compiler beta, and the behavior is different: the object is immediately deallocated on a = nil as you would expect. This is a good example of ARC getting smarter while still keeping the same basic promise.

Matt Wilding
  • 20,115
  • 3
  • 67
  • 95
0

ARC will help you to release and retain object but.... what exact time will the object be free.

You should read about non-ARC and then ARC. There are too many guy on stackoverflow said about it

(you can read this: ARC - The meaning of __unsafe_unretained?)

Community
  • 1
  • 1
Tony
  • 4,311
  • 26
  • 49