首先我们来了解一下NSHashTable
NSHashTable效仿了NSSet(NSMutableSet),但提供了比NSSet更多的操作选项,尤其是在对弱引用关系的支持上,NSHashTable在对象/内存处理时更加的灵活。相较于NSSet,NSHashTable具有以下特性:
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. [self testWeakMemory]; }
把要观察的对象加入到HashTable中
- (void)testWeakMemory { if (!_hashTablele) { _hashTablele = [NSHashTable weakObjectsHashTable]; _obj = [[NSObject alloc] init]; [_hashTablele addObject:_obj]; NSLog(@"hashTablele: %@", _hashTablele); }
HashTable中判断该对象是否存在,如果不存在就被释放了
- (void)viewWillDisappear:(BOOL)animated [super viewWillDisappear:animated]; self.obj = nil; if ([_hashTablele containsObject:_obj]) { NSLog(@"obj 对象没有被释放");