美文网首页
iOS weak的实现原理

iOS weak的实现原理

作者: RingKun | 来源:发表于2020-06-29 13:36 被阅读0次
    static NSMutableDictionary *weaks;
    
    struct OjcP {
        Class isa;
        //...
    };
    
    static NSNumber *objHeapAddress(id obj) {
        struct OjcP *heapObj = (__bridge struct OjcP *)(obj);
        return @((long)&(heapObj->isa));
    }
    
    @interface ReleasableObject : NSObject
    
    @end
    @implementation ReleasableObject
    
    -(void)dealloc {
        [super dealloc];
        NSLog(@"--- ReleasableObject dealloc ---");
        id p = [weaks objectForKey:objHeapAddress(self)];
        id *p1 = (id *)[p longValue];
        NSLog(@"读取弱指针地址:%p", p1);
        *p1 = nil;
    }
    
    @end
    
    int main(int argc, const char * argv[]) {
        NSObject *obj;
        NSObject *weak_p;
        @autoreleasepool {
            
            // 弱引用
            obj = [[ReleasableObject alloc] init];
            weak_p = obj;
            NSLog(@"存储弱指针地址:%p", &weak_p);
    //        NSLog(@"%@",  weak_p);
            // 方法1
    //        weak_p = nil;
            // 方法2
    //        id *p = &weak_p;
    //        *p = nil;
            // 方法3
            weaks = [[NSMutableDictionary alloc] init];
            // 弱指针地址
            long p11 = (long)(&weak_p);
            // 堆内存中对象isa地址
            [weaks setObject:@(p11) forKey:objHeapAddress(obj)];
            
            // 释放对象
            [obj release];
        }
        // 崩溃代码
        NSLog(@"%@",  weak_p);
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:iOS weak的实现原理

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