我试图实现ISA混写,因为我需要一些动作某个对象的dealloc方法发生。 我重写 - (类)类; 方法返回原始类(如志愿一样)。 一切工作正常,直到我尝试观察者添加到绞合的对象。 它只是崩溃。
- 在00000000 00000000()
- 0x0091d22a在_NSKeyValueRetainedObservationInfoForObject()
- 0x0092ec88在 - [NSObject的(NSKeyValueObserverRegistration)_addObserver:forProperty:选择:上下文:]()
- 0x0092d6fd在 - [NSObject的(NSKeyValueObserverRegistration)的addObserver:forKeyPath:选择:上下文:]()
下面是实现混写的
- (void)swizzleClass
{
NSString *proxyClassName = [NSString stringWithFormat:@"MDSwizzled_%@", NSStringFromClass(self->isa)];
Class proxyClass = NSClassFromString(proxyClassName);
if (!proxyClass)
proxyClass = [self createProxyClassWithName:proxyClassName];
object_setClass(self, proxyClass);
}
- (Class)createProxyClassWithName:(NSString *)proxyClassName
{
const char *c_proxyClassName = [proxyClassName cStringUsingEncoding:NSUTF8StringEncoding];
Class proxyClass = objc_allocateClassPair(self->isa, c_proxyClassName, 0);
Class dummyClass = [MDDummy class];
class_addMethodFromClass(proxyClass, dummyClass, @selector(dealloc));
class_addMethodFromClass(proxyClass, dummyClass, @selector(class));
objc_registerClassPair(proxyClass);
return proxyClass;
}
MDDummy它只是一个在convinietn方式类保持的方法(也就是这一点,并添加原料的功能没有区别)。
@implementation MDDummy
- (void)dealloc
{
//Special thinngs
[super dealloc];
}
- (Class)class
{
return //original class;
}
@end
编辑:
下面是实现class_addMethodFromClass功能:
void class_addMethodFromClass(Class class, Class sourceClass, SEL selector)
{
Method method = class_getInstanceMethod(sourceClass, selector);
IMP methodImplementation = method_getImplementation(method);
const char *types = method_getTypeEncoding(method);
class_addMethod(class, selector, methodImplementation, types);
}