错误动态继承一个UIViewController
问题描述:
摘要
我试图动态子类对象的dealloc之前做一些清理工作。我向该对象添加一个子类并添加我自己的dealloc方法,进行清理,然后调用[super dealloc]
。这适用于大多数情况,但是当它发生在UIViewControllers时,我遇到了一些奇怪的事情。看起来有些清理不是在dealloc中发生的,因为当-hash被发送到释放视图控制器时,我正在崩溃。错误动态继承一个UIViewController
在为新视图控制器创建视图时,会发生这种情况,并且它正在UIViewController的类方法中增长一些哈希集。它似乎是视图的视图控制器的散列,因为它在方法+ [UIViewController setViewController:forView:]中。
如果我没有做我自己的dealloc方法添加到动态子类一切都很好。即使我只在我自己的dealloc版本中调用[super dealloc]
,它也会以同样的方式崩溃。
有没有人有任何想法可能会出错?除了调用[super dealloc]
之外,我还需要做其他事情,以便它仍能执行它应该执行的所有操作吗?
守则
dealloc方法是这样的:
- (void)deallocWithRemoveAllAssociatedBindings {
[[BindingManager sharedInstance] removeAllBindingsAssociatedWithObject:self];
[super dealloc];
}
我的动态交叉混合的方法是这样的:
+ (void)createSubclassForObject:(id)object {
Class objectClass = object_getClass(object);
NSString *objectClassString = NSStringFromClass(objectClass);
NSString *subclassName = [NSString stringWithFormat:@"RemoveAllAssociatedBindings_%@", objectClassString];
Class subclass = objc_getClass([subclassName UTF8String]);
if (!subclass) {
subclass = objc_allocateClassPair(objectClass, [subclassName UTF8String], 0);
if (subclass) {
Method dealloc = class_getInstanceMethod(self, @selector(deallocWithRemoveAllAssociatedBindings));
class_addMethod(subclass, @selector(dealloc), method_getImplementation(dealloc), method_getTypeEncoding(dealloc));
[self addRemoveMethodToClass:subclass];
objc_registerClassPair(subclass);
}
}
if (!!subclass) {
object_setClass(object, subclass);
}
}
你可以看到在github的完整代码:https://github.com/drewag/property-bindings
答
你不应该自己调用dealloc,t帽子苹果的工作。我的建议是重写标准的dealloc方法,并添加if语句所需的任何检查以执行您的“自定义dealloc”内容。或者你可以在dealloc中调用你自定义的dealloc,就像[super dealloc]被调用的方式一样......或者只是使用ARC。