Reputation: 1
I'm a little confused about retain cycle.As the pictures show,it's a retain cycle.My opinion is when running out of the scope,test0 will release,obj_ will release,so the reference count of object A and B will be one, also when this happens on test1,then the reference count will be zero,finally,free the memory.What's the problem? enter image description here enter image description here
Upvotes: 0
Views: 78
Reputation: 6398
Upon allocation test0 is retained by the local reference and has a retain count of 1. After the call to test1's setObject test0 has a retain count of 2. Upon test0's local reference passing out of scope the test0 object's reference count is decremented by one, leaving it at one. The same is true of test1 and both are left with a reference count of 1.
I think that you may be incorrectly assuming that each time the retain count of an object is decremented the references that it holds are decremented -- which is not strictly true --. test0 will "hold" its obj with a reference count of 1 until it is itself released. Since the objects reference one another their counts can never fall below 1.
@interface Test : NSObject
{
id __strong obj_;
}
-(void)setObject:(id __strong) obj_;
@end
@implementation Test
-(id)init
{
self=[super init];
return self;
}
-(void)setObject:(id __strong) obj
{
obj_ = obj;
}
@end
// ...
id test0 = [[Test alloc] init];
NSLog(@"test0 etain count is %ld", CFGetRetainCount((__bridge CFTypeRef)test0)); // 1
id test1 = [[Test alloc] init];
[test0 setObject: test1];
[test1 setObject: test0];
NSLog(@"test0 retain count is %ld", CFGetRetainCount((__bridge CFTypeRef)test0)); // 2
Upvotes: 1