gpt4 book ai didi

objective-c - 使用带有 MVVM 模式的 RACCommand,向 ViewModel 发送参数

转载 作者:行者123 更新时间:2023-12-03 10:59:01 27 4
gpt4 key购买 nike

我在我的应用程序中使用 ReactiveCocoa 框架来获得使用 MVVM 设计模式的强大功能。

所以对于每个 Controller ,我都有一个 ViewModel。并且Controller绑定(bind)到他的ViewModel。

UIButton 绑定(bind)将如下所示:

@implementation HomeController

-(void) bindViewModel {
self.viewHeader.buttonSide.rac_command = self.viewModel.execiteFullPortfolio;
}

一切正常,但是当我想将参数传递给 ViewModel 时,我不确定这样做的正确方法是什么......

假设我有一个股票的 UICollectionView,每次点击特定股票,我都想导航到该股票资料页面。
该逻辑应该在 ViewModel 上完成,但是我如何通过 RACCommand 获取库存?

我目前正在做的是:
@implementation HomeController
-(void) bindViewModel {
__unsafe_unretained HomeController *weakSelf = self;
self.viewPortfolioPusherView.scrollGainView.blockSelect = ^ (STStock *stock){
weakSelf.viewModel.selectedStock = stock;
[weakSelf.viewModel.executeGoToStock execute:[RACSignal empty]];
};

}


@implementation HomeViewModel
-(void) initialization {
self.executeGoToStock = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf moveToSelectedStock];
});
return [RACSignal empty];
}];
}
-(void) moveToSelectedStock {
[self stockProfileControllerLazy];
self.stockProfileController.stock = self.selectedStock;
[Navigator pushController:self.stockProfileController fromController:[self.delegate controller]];
}

我确定这不是最佳做法!所以我问,什么是??

谢谢 。

最佳答案

为什么不直接通过 STStock调用 execute 的实例关于命令,而不是一个空信号?

[weakSelf.viewModel.executeGoToStock execute:stock];

然后:
self.executeGoToStock = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(STStock *stock) {
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf moveToSelectedStock:stock];
});
return [RACSignal empty];
}];

你显然需要修改 moveToSelectedStock也接受一个参数。但是,我会进一步实现 RACCommand在您的 Navigator 上这样做。此外,我会为 STStock 的实例创建一个单独的 View 模型。而不是一个集合。因此,当您选择一只股票时,它可能看起来更像这样:
StockViewModel *viewModel = [[StockViewModel alloc] initWithStock:stock];
[[Navigator pushViewModel] execute:viewModel];

这显然省略了一些细节。例如,我的导航器将 View 模型类映射到 Controller 类。当 View 模型被推送时,它会创建相应的 Controller ,并将 View 模型绑定(bind)到它。

关于objective-c - 使用带有 MVVM 模式的 RACCommand,向 ViewModel 发送参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25795201/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com