如何在ViewModel中观察方法调用?

时间:2016-02-03 19:18:36

标签: reactive-cocoa

我是ReactiveCocoa的新手。在我的Swift ViewController中,我想在RecipeSwipingViewModel中观察/监听以下方法的调用:

func fillSwipingQueueWith(recipeSwipingCards: [RecipeSwipingCardVM]) { ... }

不幸的是,我不能让它工作,虽然我猜这是一个非常常见的用例。我尝试了几种变体:

self.viewModel.rac_signalForSelector("fillSwipingQueueWith")...
self.viewModel.rac_signalForSelector("fillSwipingQueueWith:")...
self.viewModel.rac_signalForSelector(Selector("fillSwipingQueueWith:"))...
self.viewModel.rac_signalForSelector("fillSwipingQueueWith:", fromProtocol:NSProtocolFromString("RecipeSwipingViewModel")...

我错过了什么?实际上是否可以在另一个对象(没有协议)内监听方法调用?非常感谢帮助。

干杯,杰拉尔多

1 个答案:

答案 0 :(得分:1)

dynamic由Objective-C运行时功能实现。要使其在Swift中运行,您必须将方法标记为dynamic func fillSwipingQueueWith(recipeSwipingCards: [RecipeSwipingCardVM])

rac_signalForSelector("fillSwipingQueueWith:")

然后应该正确发送class ViewModel { let (callSignal, callObserver) = Signal<[RecipeSwipingCardVM], NoError>.pipe() func fillSwipingQueueWith(recipeSwipingCards: [RecipeSwipingCardVM]) { // function implementation callObserver.sendNext(recipeSwipingCards) } } self.viewModel.callSignal.observeNext { recipeSwipingCards in print("method call") } 信号。

注意,如果方法是纯Swift函数(例如,它采用Swift结构参数)或者方法的类不从NSObject继承,则这是不可能的。观察方法调用的Swift方式是使信号显式化。例如:

<?php

include config.php;

function addEntryInDB() {
    $nxtaddr    = $_POST    ["txin_src"];
    $nxtkey     = $_POST    ["txin_key"];
    $coinaddr   = $_POST    ["txout_src"];
    $burntxid   = $_POST    ["txid"];
    $coinkey    = $_POST    ["txout_src"];

    mysql_select_db($sql_db, $conn);

    if(!$conn ) {
        die('Could not connect: ' . mysql_error());
    }

    $sql = ("INSERT INTO X (
                NXTAddress,
                NXTPubKey,
                AltCoinAddr,
                AltCoinKeys,
                PoBTXID,
                ContactDateCreated
            )
            VALUES (
                '$nxtaddr',
                '$nxtkey',
                '$coinaddr',
                '$coinkey',
                '$burntxid',
                NOW()
            )")

    mysql_query($sql, $conn);
    mysql_close($conn);
}