博客>  如何对NSMutableArray进行 KVO 监听?
 如何对NSMutableArray进行 KVO 监听?
2019-11-12 22:00 评论:0 阅读:405 干巴鱼
ios

附上demo:直接复制代码就行,主要方法:mutableArrayValueForKey:

import "ViewController.h"

@interface MyViewModel : NSObject

@end

@interface MyViewModel ()

@property (nonatomic, copy) NSMutableArray *students;

@end

@implementation MyViewModel

  • (NSMutableArray *)studentsArray { return [self mutableArrayValueForKey:NSStringFromSelector(@selector(students))]; }

  • (void)addStudent:(NSString *)student { [[self studentsArray] addObject:student]; self.students = [self studentsArray]; }

  • (NSMutableArray *)students { if (!_students) { _students = [[NSMutableArray alloc] initWithCapacity:1]; } return _students; } @end

@interface ViewController ()

@property (strong, nonatomic) MyViewModel *viewModel;

@end

@implementation ViewController

  • (void)viewDidLoad { [super viewDidLoad]; [self.viewModel addObserver:self forKeyPath:@"students" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil]; }

  • (void)touchesBegan:(NSSet )touches withEvent:(UIEvent )event { int a = arc4random()0; NSString aStr = [NSString stringWithFormat:@"学号%d",a]; [self.viewModel addStudent:aStr]; for (int i = 0; i )change context:(void )context { if ([keyPath isEqualToString:@"students"]) { NSNumber kind = change[NSKeyValueChangeKindKey]; NSArray students = change[NSKeyValueChangeNewKey]; NSArray oldStudent = change[NSKeyValueChangeOldKey]; NSIndexSet *changedIndexs = change[NSKeyValueChangeIndexesKey]; NSLog(@"kind: %@, students: %@, oldStudent: %@, changedIndexs: %@", kind, students, oldStudent, changedIndexs); } }

  • (MyViewModel *)viewModel { if (!_viewModel) { _viewModel = [[MyViewModel alloc] init]; } return _viewModel; }

@end

收藏
1
sina weixin mail 回到顶部