Execute block on dealloc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// NSObject+TUBlockDealloc.h | |
// ThinkGV | |
// | |
// Created by David Beck on 4/20/12. | |
// Copyright (c) 2012 ThinkUltimate LLC. All rights reserved. | |
// | |
#import <Foundation/Foundation.h> | |
@interface NSObject (TUBlockDealloc) | |
- (void)executeOnDealloc:(void(^)(void))block; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// NSObject+TUBlockDealloc.m | |
// ThinkGV | |
// | |
// Created by David Beck on 4/20/12. | |
// Copyright (c) 2012 ThinkUltimate LLC. All rights reserved. | |
// | |
#import "NSObject+TUBlockDealloc.h" | |
#import <objc/runtime.h> | |
const void *TUBlockDeallocExecuterKey = &TUBlockDeallocExecuterKey; | |
@interface _TUBlockExecuter : NSObject | |
- (void)addBlock:(void(^)(void))block; | |
@end | |
@implementation _TUBlockExecuter | |
{ | |
NSMutableArray *_deallocBlocks; | |
} | |
- (void)dealloc | |
{ | |
for (void(^block)(void) in _deallocBlocks) { | |
block(); | |
} | |
} | |
- (id)init | |
{ | |
self = [super init]; | |
if (self) { | |
_deallocBlocks = [[NSMutableArray alloc] init]; | |
} | |
return self; | |
} | |
- (void)addBlock:(void(^)(void))block | |
{ | |
[_deallocBlocks addObject:[block copy]]; | |
} | |
@end | |
@implementation NSObject (TUBlockDealloc) | |
- (void)executeOnDealloc:(void(^)(void))block | |
{ | |
_TUBlockExecuter *executer = objc_getAssociatedObject(self, TUBlockDeallocExecuterKey); | |
if (executer == nil) { | |
executer = [[_TUBlockExecuter alloc] init]; | |
objc_setAssociatedObject(self, TUBlockDeallocExecuterKey, executer, OBJC_ASSOCIATION_RETAIN); | |
} | |
[executer addBlock:block]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This works because associated objects are removed when the host object is deallocated. As long as the executer is only referenced by the host object, it will be dealloced at the same time, causing it to execute all of its blocks.