iOS monitors changes in the contents of a variable array (count)

Monitoring the changes of the array content can also be said to be monitoring the changes of the array count. (KVO directly monitors the count of the array and will report an error)

first step

Need to create a NSObject class, create a mutArr attribute. (Creating mutArr monitoring directly in controllrt does not take effect)

@interface ObserverModel : NSObject
@property (nonatomic, strong) NSMutableArray *mutArr;
@end

@implementation SystemDetailObserverModel
-(NSMutableArray *)mutArr{
    if(_mutArr == nil){
        _mutArr = [NSMutableArray array];
    }
    return _mutArr;
}
@end

Second step

Create ObserverModel objects in the controller and monitor key changes

@property (nonatomic, strong) ObserverModel *observerModel;

[_observerModel addObserver:self forKeyPath:@"mutArr" options:NSKeyValueObservingOptionNew context:nil];

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
     NSLog(@"触发了");
    if([keyPath isEqualToString:@"mutArr"]){
    }
}

third step

Change mutArr

[[self.observerModel mutableArrayValueForKeyPath:@"mutArr"] addObject:[NSNumber numberWithInteger:i]];

[[_observerModel mutableArrayValueForKeyPath:@"mutArr"] removeObject:[NSNumber numberWithInteger:indexPath.section]];

[[_observerModel mutableArrayValueForKeyPath:@"mutArr"] removeAllObjects];

last step

Call the remove observer method in dealloc, and check whether dealloc can be called correctly.

-(void)dealloc{
    NSLog(@"---------");
    [_observerModel removeObserver:self forKeyPath:@"mutArr"];
}

Guess you like

Origin blog.csdn.net/qq_28285625/article/details/104516204