Is this simple? I'm actually trying to monitor if an object changes (to determine if I should save it). Currently I just have an array in the object with a list of all of it's readwrite properties, then I loop through it after the object is created and add observers:
for ( NSString *observer in _开发者_如何学Pythonobservers ){
[self addObserver: self forKeyPath: observer options: NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context: nil];
}
It works, but if you forget to add a property to the array, obviously the observer won't be called. Does anyone know how I can just determine the object's properties at runtime? I was thinking it may be around respondsToSelector: but I haven't been able to find much on the subject.
Thanks in advance!
Properties of an object, after they have been synthesized, behave almost like ordinary object's methods, so you can do following check
if ([myObject respondsToSelector: @selector(propertyName)]) {
// your code here
}
Or if you want to use strings as selector's name:
if ([myObject respondsToSelector: NSSelectorFromString(@"propertyName")]) {
// your code here
}
Here propertyName
is a getter (it's signature name exactly corresponds to your declared property name), so if you want to check for setter presence, you should add additional expression:
[myObject respondsToSelector: @selector(setPropertyName:)])
May be this will help:
You can get list of properties in a class using class_copyPropertyList
objc_property_t * class_copyPropertyList(Class cls, unsigned int *outCount)
and then from each property you can get its name using property_getName
function and attributes using property_getAttributes function (if you need to filter read-write properties).
For more details see Objective-c Runtime Reference
精彩评论