监听对象释放。优化log输出 by upworldcjw · Pull Request #4 · bestswifter/MySampleCode · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion RunloopAndThread/RunloopAndThread.xcodeproj/project.pbxproj
14 changes: 14 additions & 0 deletions RunloopAndThread/RunloopAndThread/NSObject+DeallocBlock.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
//
// NSObject+DeallocBlock.h
// pengpeng
//
// Created by jianwei.chen on 15/9/6.
// Copyright (c) 2015年 AsiaInnovations. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface NSObject (DeallocBlock)

-(void)runAtDealloc:(dispatch_block_t)block;
@end
45 changes: 45 additions & 0 deletions RunloopAndThread/RunloopAndThread/NSObject+DeallocBlock.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
//
// NSObject+DeallocBlock.m
// pengpeng
//
// Created by jianwei.chen on 15/9/6.
// Copyright (c) 2015年 AsiaInnovations. All rights reserved.
//

#import "NSObject+DeallocBlock.h"
#import <objc/message.h>

@interface NBDeallocBlockExecutor : NSObject{
dispatch_block_t _block;
}
- (id)initWithBlock:(dispatch_block_t)block;
@end

@implementation NBDeallocBlockExecutor
- (id)initWithBlock:(dispatch_block_t)aBlock
{
self = [super init];
if (self) {
_block = [aBlock copy];
}
return self;
}
- (void)dealloc
{
_block ? _block() : nil;
}
@end


static char *dealloc_key;
@implementation NSObject (DeallocBlock)

-(void)runAtDealloc:(dispatch_block_t)block
{
if(block){
NBDeallocBlockExecutor *executor = [[NBDeallocBlockExecutor alloc] initWithBlock:block];
objc_setAssociatedObject(self, &dealloc_key, executor, OBJC_ASSOCIATION_RETAIN);//不要强应用
}
}

@end
20 changes: 17 additions & 3 deletions RunloopAndThread/RunloopAndThread/ViewController.m