strong 수식자 weak 효과 구현 (대상이 방출될 때 속성 설정nil)

1908 단어
자세히 보기
 
 
//
//  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

좋은 웹페이지 즐겨찾기