3-循环的retain 问题
人有宠物:狗
狗有主人:人
那么使用在使用两个类时,再用 #import相互导入 就会有问题,需要使用 @class
但是当两个类都要引用对方的对象进入自己的类做属性时,内存泄露的另一种情况。解决办法, 其中一个先释放(但是还有僵尸对象的问题)
另一个解决办法是一个用 retain,一个用 assign. 在person.h中,定义dog类型的 属性时用retain .在 dog.h中,定义owner时 用asiign,就可以解决。
看我们看一个狗和人循环引用的例子:
// main.m
// 08-循环引用
//
// Created by apple on 15/8/13.
//
//
#import <Foundation/Foundation.h>
#import "Person.h"
#import "Dog.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *p = [Person new];
Dog *d = [Dog new];
p.dog = d; // setDog:
d.owner = p;
[d release];
[p release];
}
return 0;
}
// Person.h
//
//
// Created by apple on 15/8/12.
//
//
#import <Foundation/Foundation.h>
@class Dog;
@interface Person : NSObject
@property (nonatomic, retain) Dog *dog;
@end
person.m 文件:
// Person.m
//
//
// Created by apple on 15/8/12.
//
//
#import "Person.h"
@implementation Person
- (void)dealloc {
[_dog release];
NSLog(@"Person 释放");
[super dealloc];
}
@end
// Created by apple on 15/8/13.
//
//
#import <Foundation/Foundation.h>
@class Person;
@interface Dog : NSObject
@property (nonatomic, assign) Person *owner; // owner 所有者
@end
// Created by apple on 15/8/13.
//
//
#import "Dog.h"
@implementation Dog
- (void)dealloc {
[_owner release];
NSLog(@"Dog dealloc");
[super dealloc];
}
@end