Notification of Property Changes in NSObject

Can I be notified of changes to all properties of an object? I would like to call selectoreach time one of the properties in NSObject is changed.

So far, I have only seen keyPathsForValuesAffectingValueForKey:what I do not want, but it constantly appears in the search results.

The specific goal that I have now is to have a "FilterModel" that has properties for the specific characteristics of the filter. When a property is changed, I would like to update UITableViewwith the new filtered results.

+4
source share
3 answers

, , Objective-C .

id yourObject;

objc_property_t* properties = class_copyPropertyList([yourObject class], &count);
NSMutableArray* propertyArray = [NSMutableArray arrayWithCapacity:count];
for (int i = 0; i < count ; i++)
{
    const char* propertyName = property_getName(properties[i]);
    NSString *stringPropertyName = [NSString  stringWithCString:propertyName encoding:NSUTF8StringEncoding]];
    [yourObject addObserver:self forKeyPath:stringPropertyName options:NSKeyValueObservingOptionNew context:nil];
}

, . , , :

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
+3

, , , .

KVO

KVO . :

addObserver:forKeyPath:options:context:

:

observeValueForKeyPath:ofObject:change:context:

, . KVO . this. KVO . KVO Developer.

NSNotifications

, , , , , , :

postNotificationName:object:userInfo:

, , , , , , keyPathsForValuesAffectingValueForKey:. , :

addObserver:selector:name:object:

NSNotificationCenter.

+4
- (id)init
{
    if(self = [super init])
    {
        unsigned int propertyCount;
        objc_property_t *properties = class_copyPropertyList([self class], &propertyCount);
        for(int i = 0; i < propertyCount; i++)[self addObserver:self forKeyPath:[NSString stringWithCString:property_getName(properties[i]) encoding:NSUTF8StringEncoding] options:NSKeyValueObservingOptionNew context:nil];
    }
    return self;
}

- (void)dealloc
{
    unsigned int propertyCount;
    objc_property_t *properties = class_copyPropertyList([self class], &propertyCount);
    for(int i = 0; i < propertyCount; i++)[self removeObserver:self forKeyPath:[NSString stringWithCString:property_getName(properties[i]) encoding:NSUTF8StringEncoding]];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSLog(@"Changed value at key path: %@", keyPath);
}
+2
source

All Articles