似乎没有内置函数来订阅对象的所有属性中的更改。
如果你不关心它究竟性能已经改变,可以改变你的类,你可以添加虚拟财产给它(使用+ keyPathsForValuesAffectingValueForKey
或+keyPathsForValuesAffecting<Key>
法)观察其他属性的变化:
// .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通知。
此外,您可以获取对象中的所有属性列表,如发布的代码中所示,并为循环中的每个人订阅KVO通知(因此您不必硬编码属性值) - 这样,如果你需要它会得到改变的属性名称。
这似乎间接,但指出我在正确的方向。 class_copyPropertyList()和property_getname()足以在每个属性上添加观察值,完全按照最初的要求。 –
那么上面的代码片段是否有更新呢? – fatuhoku
另外,这是NSManagedObjects的工作吗? – fatuhoku