使用 ReactiveCocoa 观察 NSArray 中的对象变化
Observe object change in NSArray using ReactiveCocoa
我正在创建简单的联系人应用程序以尝试学习 ReactiveCocoa 和 MVVM。
我将单元格的 ViewModel 数组存储在我的 tableView 的 ViewModel 中。当用户进入 tableView 的编辑模式时,某些单元格的 ViewModel 的某些属性可以随着用户更改单元格文本而更改。我想观察这些变化,以便 enable/disable 完成按钮和相应的 enable/disable 信号将数据保存到模型。
如何在 tableViews 视图模型中观察这些变化?
这是我尝试使用的代码片段:
-(RACSignal *)executeCheckChange {
return [RACObserve(self, cellViewModels)
map:^id(NSArray *viewModels) {
for (id viewModel in viewModels) {
if([viewModel isKindOfClass:[STContactDetailsPhoneCellViewModel class]])
{
STContactDetailsPhoneCellViewModel *phoneViewModel = (STContactDetailsPhoneCellViewModel *)viewModel;
if([phoneViewModel isChanged])
return @(YES);
}
}
return @(NO);
}];
}
但是这个RACObserve
只有在数组本身改变时才会被调用,而不是数组的元素。
在我的特殊情况下,我能够通过这种方式解决问题:
-(RACSignal *)executeChangeCheck {
@weakify(self);
return [[RACObserve(self, cellViewModels)
map:^(NSArray *viewModels) {
RACSequence *selectionSignals = [[viewModels.rac_sequence
filter:^BOOL(id value) {
return [value isKindOfClass:[STContactDetailsPhoneCellViewModel class]];
}]
map:^(STContactDetailsPhoneCellViewModel *viewModel) {
@strongify(self);
return [RACObserve(viewModel, editPhone)
map:^id(NSString *editPhone) {
return @(![editPhone isEqualToString:viewModel.phone]);
}];
}];
return [[RACSignal
combineLatest:selectionSignals]
or];
}]
switchToLatest];
}
总而言之,每当我的数组发生变化时,我都会在每个 ViewModel 上创建一组观察值,以我只观察到我感兴趣的那些的方式过滤它们,将观察值与原始值进行比较并确保只有最新的信号生效。
要观察 class 属性的变化,您需要使用键值观察功能向 属性 添加观察者。
我正在创建简单的联系人应用程序以尝试学习 ReactiveCocoa 和 MVVM。 我将单元格的 ViewModel 数组存储在我的 tableView 的 ViewModel 中。当用户进入 tableView 的编辑模式时,某些单元格的 ViewModel 的某些属性可以随着用户更改单元格文本而更改。我想观察这些变化,以便 enable/disable 完成按钮和相应的 enable/disable 信号将数据保存到模型。 如何在 tableViews 视图模型中观察这些变化?
这是我尝试使用的代码片段:
-(RACSignal *)executeCheckChange {
return [RACObserve(self, cellViewModels)
map:^id(NSArray *viewModels) {
for (id viewModel in viewModels) {
if([viewModel isKindOfClass:[STContactDetailsPhoneCellViewModel class]])
{
STContactDetailsPhoneCellViewModel *phoneViewModel = (STContactDetailsPhoneCellViewModel *)viewModel;
if([phoneViewModel isChanged])
return @(YES);
}
}
return @(NO);
}];
}
但是这个RACObserve
只有在数组本身改变时才会被调用,而不是数组的元素。
在我的特殊情况下,我能够通过这种方式解决问题:
-(RACSignal *)executeChangeCheck {
@weakify(self);
return [[RACObserve(self, cellViewModels)
map:^(NSArray *viewModels) {
RACSequence *selectionSignals = [[viewModels.rac_sequence
filter:^BOOL(id value) {
return [value isKindOfClass:[STContactDetailsPhoneCellViewModel class]];
}]
map:^(STContactDetailsPhoneCellViewModel *viewModel) {
@strongify(self);
return [RACObserve(viewModel, editPhone)
map:^id(NSString *editPhone) {
return @(![editPhone isEqualToString:viewModel.phone]);
}];
}];
return [[RACSignal
combineLatest:selectionSignals]
or];
}]
switchToLatest];
}
总而言之,每当我的数组发生变化时,我都会在每个 ViewModel 上创建一组观察值,以我只观察到我感兴趣的那些的方式过滤它们,将观察值与原始值进行比较并确保只有最新的信号生效。
要观察 class 属性的变化,您需要使用键值观察功能向 属性 添加观察者。