Skip to content

Commit

Permalink
fix: 尝试兜底修复 target 被释放导致的 crash,释放原因未知 #17
Browse files Browse the repository at this point in the history
  • Loading branch information
yulingtianxia committed Jul 23, 2022
1 parent 8d60600 commit 038fddc
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
3 changes: 1 addition & 2 deletions MTDemo/MTDemo/ViewController.m
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,7 @@ - (void)didReceiveMemoryWarning {
// Dispose of any resources that can be recreated.
}

- (void)handleFooNotification:(NSNotification *)notification
{
- (void)handleFooNotification:(NSNotification *)notification {
NSDate *date = notification.userInfo[@"arg"];
NSDateFormatter *df = [NSDateFormatter new];
[df setDateFormat:@"dd/MM/yyyy\nHH:mm:ss"];
Expand Down
16 changes: 12 additions & 4 deletions MessageThrottle/MessageThrottle.m
Original file line number Diff line number Diff line change
Expand Up @@ -170,13 +170,17 @@ - (NSString *)description {

#pragma mark Private Method

- (MTDealloc *)deallocObject {
MTDealloc *mtDealloc = objc_getAssociatedObject(self.target, self.selector);
- (nullable MTDealloc *)deallocObject {
id target = self.target;
if (!target) {
return nil;
}
MTDealloc *mtDealloc = objc_getAssociatedObject(target, self.selector);
if (!mtDealloc) {
mtDealloc = [MTDealloc new];
mtDealloc.rule = self;
mtDealloc.cls = object_getClass(self.target);
objc_setAssociatedObject(self.target, self.selector, mtDealloc, OBJC_ASSOCIATION_RETAIN);
mtDealloc.cls = object_getClass(target);
objc_setAssociatedObject(target, self.selector, mtDealloc, OBJC_ASSOCIATION_RETAIN);
}
return mtDealloc;
}
Expand All @@ -188,6 +192,10 @@ - (void)invokingLastInvocation {
// 判断 target 现在的类型和之前 hook 时的类型的子类(或相同)
// 如果判断成立,则可以正常 invoke;否则说明 isa 指针被其他程序修改过了,需要重新 apply rule,修正 isa。
MTDealloc *mtDealloc = [self deallocObject];
// 如果获取不到 mtDealloc,是因为 self.target 已经析构了,所以也没必要再执行方法了
if (!mtDealloc) {
return;
}
Class originalClass = object_getClass(self.target);
BOOL valid = [originalClass isSubclassOfClass:mtDealloc.cls];
if (!valid) {
Expand Down

0 comments on commit 038fddc

Please sign in to comment.