美文网首页
OC对象弱引用

OC对象弱引用

作者: 扯淡的青春_ | 来源:发表于2018-07-22 22:18 被阅读0次

    对象添加到集合引用计数不+1的几种方式:

    1.weakObject

    TestModel *model = [[TestModel alloc] init];
    NSLog(@"添加集合前:%ld", (long)CFGetRetainCount((__bridge CFTypeRef)model)); // RetainCount:1
    
    // @property (nonatomic, weak) id value;
    WeakObject *wo = [[WeakObject alloc] init];
    wo.value = model;
    
    NSMutableArray *array = [[NSMutableArray alloc] init];
    [array addObject:wo];
    NSLog(@"添加集合后:%ld", (long)CFGetRetainCount((__bridge CFTypeRef)model)); // RetainCount:1
    
    

    2.NSHashTable

    TestModel *model = [[TestModel alloc] init];
    NSLog(@"添加集合前:%ld", (long)CFGetRetainCount((__bridge CFTypeRef)model)); // RetainCount:1
    
    NSHashTable *hashTable = [NSHashTable hashTableWithOptions:NSPointerFunctionsWeakMemory];
    [hashTable addObject:model];
    
    NSLog(@"添加集合后:%ld", (long)CFGetRetainCount((__bridge CFTypeRef)model)); // RetainCount:1
    

    3.NSMapTable

    TestModel *model = [[TestModel alloc] init];
    NSLog(@"添加集合前:%ld", (long)CFGetRetainCount((__bridge CFTypeRef)model)); // RetainCount:1
    
    NSMapTable *mapTable = [NSMapTable weakToWeakObjectsMapTable];
    [mapTable setObject:model forKey:@"test"];
    
    NSLog(@"添加集合后:%ld", (long)CFGetRetainCount((__bridge CFTypeRef)model)); // RetainCount:1
    

    4.NSPointerArray

    TestModel *model = [[TestModel alloc] init];
    NSLog(@"添加集合前:%ld", (long)CFGetRetainCount((__bridge CFTypeRef)model)); // RetainCount:1
    
    NSPointerArray *pointerArray = [NSPointerArray weakObjectsPointerArray];
    [pointerArray addPointer:(__bridge void * _Nullable)(model)];
    
    NSLog(@"添加集合后:%ld", (long)CFGetRetainCount((__bridge CFTypeRef)model)); // RetainCount:1
    

    相关文章

      网友评论

          本文标题:OC对象弱引用

          本文链接:https://www.haomeiwen.com/subject/gmbrmftx.html