Last active
October 16, 2021 13:08
-
-
Save aegzorz/6068741 to your computer and use it in GitHub Desktop.
Category on NSObject that logs deallocs, useful when tracking down memory leaks
This file contains hidden or 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
#import <Foundation/Foundation.h> | |
@interface NSObject (LogDealloc) | |
- (void)logOnDealloc; | |
@end |
This file contains hidden or 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
#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 |
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
how to use it, it seems not work in my arc project~~