main.m
#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;
}
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;//装B写法
[super dealloc];
}
@end
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;//由于Dog没有对Person进行retain操作所以没必要进行release操作。
[super dealloc];
}
@end