// main.m // 循环retain #import <Foundation/Foundation.h> #import "Person.h" #import "Dog.h" int main(int argc, const char * argv[]) { Person *p = [Person new]; Dog *d = [Dog new]; // 如果A对用要拥有B对象, 而B对应又要拥有A对象, 此时会形成循环retain // 如何解决这个问题: 不要让A retain B, B retain A // 让其中一方不要做retain操作即可 p.dog = d; // retain d.owner = p; // retain assign [p release]; [d release]; return 0; }
// Dog.h #import <Foundation/Foundation.h> @class Person; @interface Dog : NSObject //@property(nonatomic, retain)Person *owner; @property(nonatomic, assign)Person *owner; @end
// Dog.m #import "Dog.h" #import "Person.h" @implementation Dog -(void)dealloc { NSLog(@"%s", __func__); // [_owner release]; // self.owner = nil; [super dealloc]; } @end
// // Person.h #import <Foundation/Foundation.h> @class Dog; @interface Person : NSObject @property(nonatomic, retain)Dog *dog; @end
// Person.m #import "Person.h" #import "Dog.h" @implementation Person - (void)dealloc { NSLog(@"%s", __func__); // [_dog release]; self.dog = nil; [super dealloc]; } @end
本文转自农夫山泉别墅博客园博客,原文链接:http://www.cnblogs.com/yaowen/p/7428389.html,如需转载请自行联系原作者