Skip to content

Commit 038fddc

Browse files
committed
fix: 尝试兜底修复 target 被释放导致的 crash,释放原因未知 #17
1 parent 8d60600 commit 038fddc

2 files changed

Lines changed: 13 additions & 6 deletions

File tree

MTDemo/MTDemo/ViewController.m

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,8 +70,7 @@ - (void)didReceiveMemoryWarning {
7070
// Dispose of any resources that can be recreated.
7171
}
7272

73-
- (void)handleFooNotification:(NSNotification *)notification
74-
{
73+
- (void)handleFooNotification:(NSNotification *)notification {
7574
NSDate *date = notification.userInfo[@"arg"];
7675
NSDateFormatter *df = [NSDateFormatter new];
7776
[df setDateFormat:@"dd/MM/yyyy\nHH:mm:ss"];

MessageThrottle/MessageThrottle.m

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -170,13 +170,17 @@ - (NSString *)description {
170170

171171
#pragma mark Private Method
172172

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

0 commit comments

Comments
 (0)