strong修饰符实现weak效果(对象释放时,属性置nil)

阅读更多

 

 

//
//  NSObject+EZ_Dealloc.h
//  EZToolKit
//
//  Created by yangjun zhu on 2017/1/6.
//  Copyright © 2017年 Cactus. All rights reserved.
//

#import 
typedef void (^voidBlock)(void);

@interface EZBlockExecutor : NSObject

- (id)initWithBlock:(voidBlock)block;

@end
@interface NSObject (EZ_Dealloc)
- (void)ez_runAtDealloc:(voidBlock)block;

@end

 

//
//  NSObject+EZ_Dealloc.m
//  EZToolKit
//
//  Created by yangjun zhu on 2017/1/6.
//  Copyright © 2017年 Cactus. All rights reserved.
//

#import "NSObject+EZ_Dealloc.h"
#import 

@interface EZBlockExecutor() {
    voidBlock _block;
}
@end


@implementation EZBlockExecutor
- (id)initWithBlock:(voidBlock)aBlock
{
    self = [super init];
    
    if (self) {
        _block = [aBlock copy];
    }
    
    return self;
}

- (void)dealloc
{
    _block ? _block() : nil;
}

@end

const void *runAtDeallocBlockKey = &runAtDeallocBlockKey;

@implementation NSObject (EZ_Dealloc)
- (void)ez_runAtDealloc:(voidBlock)block{
    if (block) {
        EZBlockExecutor *executor = [[EZBlockExecutor alloc] initWithBlock:block];
        
        objc_setAssociatedObject(self,
                                 runAtDeallocBlockKey,
                                 executor,
                                 OBJC_ASSOCIATION_RETAIN);
    }
}
@end

 https://github.com/easyui/EZToolKit/blob/master/EZToolKit/EZCategory/Foundation/NSObject/NSObject%2BEZ_Dealloc.m

你可能感兴趣的:(strong修饰符实现weak效果(对象释放时,属性置nil))