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對(duì)用要擁有B對(duì)象, 而B對(duì)應(yīng)又要擁有A對(duì)象, 此時(shí)會(huì)形成循環(huán)retain
// 如何解決這個(gè)問題: 不要讓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沒有對(duì)Person進(jìn)行retain操作所以沒必要進(jìn)行release操作醉旦。
[super dealloc];
}
@end
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者