观察 Objective-C 中任何类属性的变化 [英] Observing a Change to ANY Class Property in Objective-C

查看:20
本文介绍了观察 Objective-C 中任何类属性的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单地说,有没有办法在 Objective-C 类中的任何属性发生更改时接收一般通知?我知道我可以使用 KVO 来监视特定的属性更改,但是每当任何 setProperty: 消息发送到我的类时,我都需要调用特定的方法.我希望能够收到通用通知,而无需担心具体修改了哪个属性.

Put simply, is there a way to receive a general notification when any property in an Objective-C class is changed? I know I can use KVO to monitor particular property changes, but I have the need to call a particular method whenever any setProperty: message is sent to my class. I want to be able to receive a generic notification without any concern about which property in particular was modified.

如果它有助于澄清我为什么要这样做,我正在使用这里找到的一些快速表格滚动代码:http://blog.atebits.com/2008/12/fast-scrolling-in-tweetie-with-uitableview/

If it helps to clarify why I want to do this, I am making use of some fast table scrolling code found here: http://blog.atebits.com/2008/12/fast-scrolling-in-tweetie-with-uitableview/

完成此操作的部分过程是,每当修改表视图单元格中的属性时,都需要调用 [ self setNeedsDisplay ].我宁愿不必为了进行此调用而覆盖类中每个属性的 setter 方法.

Part of the process of accomplishing this is that whenever a property in a table view cell is modified, [ self setNeedsDisplay ] needs to be called. I'd rather not have to override the setter methods for every property in my class just to make this call.

推荐答案

正如 Chuck 所指出的,你可以创建一个依赖键,当然你也可以直接观察所有的属性(这比重载 setter 工作更少).

As Chuck notes, you can create a dependent key, or of course you can directly observe all the properties (which is less work than overloading the setters).

使用 Objective-C 运行时,如果您专门使用属性,则可以使用 class_copyPropertyList().但如果这个问题对你来说有点问题,我可能只会这样做.如果您只有一个此问题的实例,那么直接观察属性列表可能更容易、更安全且更易于维护,除非您喜欢在 ObjC 运行时中工作.

Using the Objective-C runtime, if you exclusively use properties, you can automate this process using class_copyPropertyList(). But I'd probably only do this if this problem comes up a bit for you. If you only have one instance of this problem, it's probably easier and safer and more maintainable just to directly observe the list of properties unless you feel like working in the ObjC runtime.

这篇关于观察 Objective-C 中任何类属性的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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