Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Category on NSObject that logs deallocs, useful when tracking down memory leaks
#import <Foundation/Foundation.h>
@interface NSObject (LogDealloc)
- (void)logOnDealloc;
@end
#import "NSObject+LogDealloc.h"
#import <objc/runtime.h>
static char __logDeallocAssociatedKey__;
@interface LogDealloc : NSObject
@property (strong) NSString* message;
@end
@implementation NSObject (LogDealloc)
- (void)logOnDealloc
{
if( objc_getAssociatedObject( self, &__logDeallocAssociatedKey__ ) == nil ) {
LogDealloc* log = [[LogDealloc alloc] init];
log.message = NSStringFromClass( self.class );
objc_setAssociatedObject( self, &__logDeallocAssociatedKey__, log, OBJC_ASSOCIATION_RETAIN );
}
}
@end
@implementation LogDealloc
- (void)dealloc
{
NSLog( @"dealloc: %@", self.message );
}
@end

how to use it, it seems not work in my arc project~~

Cool trick. I would just mention that associated objects are released after dealloc.

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