面试题答案
一键面试实现思路
- 强引用与弱引用:对于非循环引用的子对象,主对象通常使用强引用持有。对于可能产生循环引用的关系,使用弱引用(在ARC环境下)或__unsafe_unretained(在MRC环境下)来打破循环。
- 手动内存管理(MRC):在MRC环境下,需要在主对象的dealloc方法中手动释放所有强引用的子对象。
- 自动引用计数(ARC):在ARC环境下,系统会自动管理内存,但仍需正确处理循环引用以确保对象能被正确释放。
关键代码片段
ARC环境
假设主对象是MainObject
,有两个可能产生循环引用的子对象SubObjectA
和SubObjectB
。
// MainObject.h
#import <Foundation/Foundation.h>
@class SubObjectA;
@class SubObjectB;
@interface MainObject : NSObject
@property (nonatomic, strong) SubObjectA *subObjectA;
@property (nonatomic, weak) SubObjectB *subObjectB;
@end
// SubObjectA.h
#import <Foundation/Foundation.h>
@class SubObjectB;
@interface SubObjectA : NSObject
@property (nonatomic, weak) SubObjectB *subObjectB;
@end
// SubObjectB.h
#import <Foundation/Foundation.h>
@class SubObjectA;
@interface SubObjectB : NSObject
@property (nonatomic, weak) SubObjectA *subObjectA;
@end
MRC环境
// MainObject.h
#import <Foundation/Foundation.h>
@class SubObjectA;
@class SubObjectB;
@interface MainObject : NSObject
@property (nonatomic, retain) SubObjectA *subObjectA;
@property (nonatomic, unsafe_unretained) SubObjectB *subObjectB;
- (void)dealloc;
@end
// MainObject.m
#import "MainObject.h"
#import "SubObjectA.h"
#import "SubObjectB.h"
@implementation MainObject
- (void)dealloc {
[_subObjectA release];
[super dealloc];
}
@end
// SubObjectA.h
#import <Foundation/Foundation.h>
@class SubObjectB;
@interface SubObjectA : NSObject
@property (nonatomic, unsafe_unretained) SubObjectB *subObjectB;
- (void)dealloc;
@end
// SubObjectA.m
#import "SubObjectA.h"
#import "SubObjectB.h"
@implementation SubObjectA
- (void)dealloc {
[super dealloc];
}
@end
// SubObjectB.h
#import <Foundation/Foundation.h>
@class SubObjectA;
@interface SubObjectB : NSObject
@property (nonatomic, unsafe_unretained) SubObjectA *subObjectA;
- (void)dealloc;
@end
// SubObjectB.m
#import "SubObjectB.h"
#import "SubObjectA.h"
@implementation SubObjectB
- (void)dealloc {
[super dealloc];
}
@end