Code:
#import <Foundation/Foundation.h>
// ARC机制中,循环引用的解决办法:
// 在会产生循环引用的地方
// 一端的@property参数使用关键字strong修饰
// 另一端的@property参数使用关键字weak修饰
@class Dog;
@interface Person : NSObject
// strong
@property (nonatomic, strong) Dog* dog;
@end
@implementation Person
- (void)dealloc {
NSLog(@"Person-dealloc");
}
@end
@interface Dog : NSObject
// weak
@property (nonatomic, weak) Person* person;
@end
@implementation Dog
- (void)dealloc {
NSLog(@"Dog-dealloc");
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person* p = [[Person alloc] init];
Dog* d = [[Dog alloc] init];
[p setDog:d];
[d setPerson:p];
}
return 0;
}Output:
Person-dealloc
Dog-dealloc
本文介绍了解决Objective-C中自动引用计数(ARC)机制下循环引用的问题。通过使用不同的内存管理属性,在Person和Dog两个类之间避免了循环引用的发生。
6400

被折叠的 条评论
为什么被折叠?



