pragma mark 循环retain
pragma mark 概念
/**
循环retain
你拥有我,我拥有你
释放的时候没有办法释放成功
*/
pragma mark 代码
#import <Foundation/Foundation.h>
#pragma mark 类
#import "Person.h"
#import "Dog.h"
#pragma mark main函数
int main(int argc, const char * argv[])
{
Person *p = [Person new];
Dog *d = [Dog new];
// 如果A对象要拥有B对象,而B对象又要拥有A对象,此时会形成循环retain
#warning 如何解决循环retain
// 不要让A retain B , B retain A
// 让其中一方不要retain操作即可
p.dog = d; // 人 有一条狗 retain
d.owner = p; // 狗 有一个主人 assign
/*
Person object 0x1007000a0 overreleased while already deallocating; break on objc_overrelease_during_dealloc_error to debug
// 野指针错误 开启僵尸对象 edit Scheme -> Run -> diagnostic -> Enable Zombie Objects
[Person release]: message sent to deallocated instance 0x100605d80
把release操作交换一下 即可
// 如果不交换 可以直接把dog中的dealloc中的 [_owner release]; 注释即可
[p release];
[d release];
*/
// 这里会出现过度释放,潜在的隐患
// 解决办法是 最好在dealloc 里面设置setter方法为nil
// 在dealloc里面 只要调用setter方法 =nil 怎么写都不会报错 self.owner = nil、self.dog = nil
[d release];
[p 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;
[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
{
// [_owner release]; assgin 就不需要release
self.owner = nil;
NSLog(@"%s",__func__);
[super dealloc];
}
@end
网友评论