首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >RACSignal用于对象的NSArray

RACSignal用于对象的NSArray
EN

Stack Overflow用户
提问于 2013-10-30 20:44:36
回答 1查看 2.9K关注 0票数 4

我在我的NSArray上有一个ViewModel对象:

@property (非原子的,强的) NSArray *viewModel;

ViewModel对象如下所示:

代码语言:javascript
复制
@interface ViewModel : NSObject

@property (nonatomic) BOOL isSelected;

@end

我试图在RACCommand的init方法上为RACSignal创建一个enabledSignal:

代码语言:javascript
复制
- (id)initWithEnabled:(RACSignal *)enabledSignal signalBlock:(RACSignal * (^)(id input))signalBlock

如果选择了0 viewModel对象,或者所选viewModels的数量等于viewModels的总数,则此信号将通知命令启用。

我可以创建一个RACSequence,它将为我提供由以下代码选择的viewModel对象:

代码语言:javascript
复制
RACSequence *selectedViewModels = [[self.viewModels.rac_sequence

                                        filter:^BOOL(ViewModel *viewModel) {
                                            return viewModel.isSelected == YES;
                                        }]

                                       map:^id(ViewModel *viewModel) {
                                           return viewModel;
                                       }];

如何创建有效的信号?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-10-31 15:46:42

要观察更改的所有最新视图模型(仅包括最新的视图模型),我们需要在每次数组更改时设置新的KVO观测。

最自然的方式来表示这是一个信号信号。每个“内部”信号代表对一个版本的viewModels的一组观察,然后我们将使用-switchToLatest来确保只有最新的信号生效:

代码语言:javascript
复制
@weakify(self);

RACSignal *enabled = [[RACObserve(self, viewModels)
    // Map _each_ array of view models to a signal determining whether the command
    // should be enabled.
    map:^(NSArray *viewModels) {
        RACSequence *selectionSignals = [[viewModels.rac_sequence
            map:^(ViewModel *viewModel) {
                // RACObserve() implicitly retains `self`, so we need to avoid
                // a retain cycle.
                @strongify(self);

                // Observe each view model's `isSelected` property for changes.
                return RACObserve(viewModel, isSelected);
            }]
            // Ensure we always have one YES for the -and below.
            startWith:[RACSignal return:@YES]];

        // Sends YES whenever all of the view models are selected, NO otherwise.
        return [[RACSignal
            combineLatest:selectionSignals]
            and];
    }]
    // Then, ensure that we only subscribe to the _latest_ signal returned from
    // the block above (i.e., the observations from the latest `viewModels`).
    switchToLatest];
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19693443

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档