问题描述
我对使用键值观察(KVO)以及如何注册以接收属性更改通知感到满意:
I am happy with the use of Key Value Observing (KVO), and how to register to receive notifications of property change:
[account addObserver:inspector
forKeyPath:@"openingBalance"
options:NSKeyValueObservingOptionNew
context:NULL];
但是,如果我想观察帐户对象所有属性的变化,该如何实现?我必须注册每个属性的通知通知吗?
However, if I want to observe changes in all the properties of the account object, how can I achieve this? Do I have to register for notification for each and every property?
推荐答案
似乎没有内置函数可以订阅对象所有属性的更改.
It seems there's no built-in function to subscribe for changes in all properties of the objects.
如果您不关心确切地更改了哪个属性,并且可以更改您的类,则可以向其添加虚拟属性以观察其他属性的更改(使用+ keyPathsForValuesAffectingValueForKey
或+keyPathsForValuesAffecting<Key>
方法):
If you don't care about which exactly property has changed and can change your class you can add dummy property to it to observe changes in other properties (using + keyPathsForValuesAffectingValueForKey
or +keyPathsForValuesAffecting<Key>
method):
// .h. We don't care about the value of this property, it will be used only for KVO forwarding
@property (nonatomic) int dummy;
#import <objc/runtime.h>
//.m
+ (NSSet*) keyPathsForValuesAffectingDummy{
NSMutableSet *result = [NSMutableSet set];
unsigned int count;
objc_property_t *props = class_copyPropertyList([self class], &count);
for (int i = 0; i < count; ++i){
const char *propName = property_getName(props[i]);
// Make sure "dummy" property does not affect itself
if (strcmp(propName, "dummy"))
[result addObject:[NSString stringWithUTF8String:propName]];
}
free(props);
return result;
}
现在,如果您观察dummy
属性,则每次更改对象的任何属性时,都会收到KVO通知.
Now if you observe dummy
property you'll get KVO notification each time any of object's properties is changed.
此外,您还可以像发布的代码中那样获取对象中所有属性的列表,并循环地为每个属性订阅KVO通知(这样就不必对属性值进行硬编码)-这样,您就可以如果需要,可以更改属性名称.
Also you can get list of all properties in the object as in the code posted and subscribe for KVO notifications for each of them in a loop (so you don't have to hard code property values) - this way you'll get changed property name if you need it.
这篇关于键值观察-如何观察对象的所有属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!