Skip to content

Instantly share code, notes, and snippets.

@KittenYang
Created September 27, 2016 16:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save KittenYang/9daa39541f3cff2cef026e51bdc0de4b to your computer and use it in GitHub Desktop.
Save KittenYang/9daa39541f3cff2cef026e51bdc0de4b to your computer and use it in GitHub Desktop.
监控指定对象是否正常释放
#import <objc/runtime.h>
void Swizzle(Class c, SEL orig, SEL new) {
Method origMethod = class_getInstanceMethod(c, orig);
Method newMethod = class_getInstanceMethod(c, new);
if (class_addMethod(c, orig, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))){
class_replaceMethod(c, new, method_getImplementation(origMethod), method_getTypeEncoding(origMethod));
} else {
method_exchangeImplementations(origMethod, newMethod);
}
}
@implementation NSObject (MMAdd)
- (void)setShouldLogWhenDealloc:(BOOL)shouldLogWhenDealloc {
objc_setAssociatedObject(self, @selector(shouldLogWhenDealloc), @(shouldLogWhenDealloc),
OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (BOOL)shouldLogWhenDealloc {
return [objc_getAssociatedObject(self, @selector(shouldLogWhenDealloc)) boolValue];
}
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Swizzle(self, NSSelectorFromString(@"dealloc"), @selector(_myDealloc));
});
}
+ (NSString *)nameOfClass {
return NSStringFromClass([self class]);
}
- (void)_myDealloc {
if (self.shouldLogWhenDealloc) {
NSLog(@"----- 💀 %@ Dealloc!",NSStringFromClass([self class]));
}
[self _myDealloc];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment