08-09、A对象与B对象的“循环retain”的解决方案

2017-09-25  本文已影响0人  山中石头
Snip20170925_60.png
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
上一篇下一篇

猜你喜欢

热点阅读