Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 44 lines (36 sloc) 1.114 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
//
// NSObject+deallocBlock.m
// MapTest
//
// Created by Tom Harrington on 2/5/12.
// Copyright (c) 2012 Atomic Bird, LLC. All rights reserved.
//

#import "NSObject+deallocBlock.h"
#import <objc/runtime.h>

static char *deallocArrayKey = "deallocArrayKey";

// This class exists for the sole purpose of holding a block that it executes before getting deallocated.
@interface DeallocHandler : NSObject
@property (readwrite, copy) void (^theBlock)(void);
@end

@implementation DeallocHandler
@synthesize theBlock;

- (void)dealloc
{
    if (theBlock != nil) {
        theBlock();
    }
}
@end

@implementation NSObject (deallocBlock)

- (void)addDeallocBlock:(void (^)(void))theBlock;
{
    NSMutableArray *deallocBlocks = objc_getAssociatedObject(self, &deallocArrayKey);
    if (deallocBlocks == nil) {
        deallocBlocks = [NSMutableArray array];
        objc_setAssociatedObject(self, &deallocArrayKey, deallocBlocks, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    DeallocHandler *handler = [[DeallocHandler alloc] init];
    [handler setTheBlock:theBlock];
    [deallocBlocks addObject:handler];
}
@end
Something went wrong with that request. Please try again.