调整单个实例,而不是类 [英] Swizzling a single instance, not a class

查看:177
本文介绍了调整单个实例,而不是类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在NSObject上有一个类别应该是这样的东西。当我在一个对象上调用它时,我想覆盖它的dealloc方法进行一些清理。

I have a category on NSObject which supposed to so some stuff. When I call it on an object, I would like to override its dealloc method to do some cleanups.

我想用方法调配来做,但无法弄清楚怎么样。我发现的唯一例子是关于如何替换整个类的方法实现(在我的例子中,它将覆盖所有NSObjects的dealloc - 我不想这样做。)

I wanted to do it using method swizzling, but could not figure out how. The only examples I've found are on how to replace the method implementation for the entire class (in my case, it would override dealloc for ALL NSObjects - which I don't want to).

我想覆盖NSObject特定实例的dealloc方法。

I want to override the dealloc method of specific instances of NSObject.

@interface NSObject(MyCategory)
-(void)test;
@end

@implementation NSObject(MyCategory)
-(void)newDealloc
{
  // do some cleanup here
  [self dealloc]; // call actual dealloc method
}
-(void)test
{
  IMP orig=[self methodForSelector:@selector(dealloc)];
  IMP repl=[self methodForSelector:@selector(newDealloc)];
  if (...)   // 'test' might be called several times, this replacement should happen only on the first call
  {
     method_exchangeImplementations(..., ...);
  }
}
@end


推荐答案

你不能真正做到这一点,因为对象没有自己的方法表。只有类具有方法表,如果更改它们,它将影响该类的每个对象。但是有一种简单的方法:在运行时将对象的类更改为动态创建的子类。这种技术,也称为isa-swizzling,被Apple用来实现自动KVO。

You can't really do this since objects don't have their own method tables. Only classes have method tables and if you change those it will affect every object of that class. There is a straightforward way around this though: Changing the class of your object at runtime to a dynamically created subclass. This technique, also called isa-swizzling, is used by Apple to implement automatic KVO.

这是一种功能强大的方法,它有其用途。但对于您的情况,使用关联对象有一种更简单的方法。基本上你使用 objc_setAssociatedObject 将另一个对象关联到你的 dealloc 中进行清理的第一个对象。您可以在此博客文章中找到更多详细信息。可可是我的女朋友

This is a powerful method and it has its uses. But for your case there is an easier method using associated objects. Basically you use objc_setAssociatedObject to associate another object to your first object which does the cleanup in its dealloc. You can find more details in this blog post on Cocoa is my Girlfriend.

这篇关于调整单个实例,而不是类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆