Skip to content

Instantly share code, notes, and snippets.

@leilee
Created June 16, 2017 03:33
Show Gist options
  • Save leilee/d1475901b0026c885a7068a05c11c4b9 to your computer and use it in GitHub Desktop.
Save leilee/d1475901b0026c885a7068a05c11c4b9 to your computer and use it in GitHub Desktop.
KVO NSArray.md

AAAA.h

#import <Foundation/Foundation.h>

@interface AAAA : NSObject

@property NSMutableArray* dogs;

- (void)insertDogs:(NSArray *)array atIndexes:(NSIndexSet *)indexes;
- (void)removeDogsAtIndexes:(NSIndexSet *)indexes;

@end

@interface BBBB : AAAA

@end

@interface Observer : NSObject

- (void)test;

@end

AAAA.m

#import "AAAA.h"
@import KVOController;

@implementation AAAA

- (instancetype)init
{
    self = [super init];
    if (self)
    {
        _dogs = [NSMutableArray array];
    }
    return self;
}

- (void)insertDogs:(NSArray *)array atIndexes:(NSIndexSet *)indexes
{
    [_dogs insertObjects:array atIndexes:indexes];
    NSLog(@"do something");
}

- (void)removeDogsAtIndexes:(NSIndexSet *)indexes
{
    [_dogs removeObjectsAtIndexes:indexes];
}

@end

@implementation BBBB

- (void)insertDogs:(NSArray *)array atIndexes:(NSIndexSet *)indexes
{
    [super insertDogs:array atIndexes:indexes];
    NSLog(@"do something in subclass");
}

@end

@interface Observer ()
{
    FBKVOController* _kvo;
    BBBB* _bbbb;
}
@end

@implementation Observer

- (instancetype)init
{
    self = [super init];
    if (self)
    {
        _bbbb = [BBBB new];
        _kvo = [FBKVOController controllerWithObserver:self];
        
        [_kvo observe:_bbbb
              keyPath:@"dogs"
              options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld
                block:^(id  _Nullable observer, id  _Nonnull object, NSDictionary<NSString *,id> * _Nonnull change) {
                    NSLog(@"%@", change);
                }];
    }
    return self;
}

- (void)test
{
    [_bbbb insertDogs:@[[NSObject new]] atIndexes:[NSIndexSet indexSetWithIndex:0]];
}

@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment