Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Execute block on dealloc
//
// 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
//
// 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
@davbeck
Copy link
Author

davbeck commented Nov 29, 2012

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment