簡體   English   中英

使用Swift閉包與Objective-C框架

[英]Using Swift closure with Objective-C framework

我正在使用MCSwipeTableViewCell框架進行可滑動的tableviewcells。 cellForRowAtIndexPath函數中的一個完成塊如下所示:

[cell setSwipeGestureWithView:checkView color:greenColor mode:MCSwipeTableViewCellModeSwitch state:MCSwipeTableViewCellState1 completionBlock:^(MCSwipeTableViewCell *cell, MCSwipeTableViewCellState state, MCSwipeTableViewCellMode mode) {
      // run some function call
}];

我使用Bridging-Header文件將框架導入我的Swift項目,並嘗試在Swift中使用相同的完成塊。 這就是我所擁有的:

cell.setSwipeGestureWithView(crossView, color: UIColor.colorFromRGB(RED), mode: MCSwipeTableViewCellMode.Switch, state:MCSwipeTableViewCellState.State1, completionBlock: { (cell: MCSwipeTableViewCell!, state: MCSwipeTableViewCellState!, mode: MCSwipeTableViewCellMode!) -> Void in
    self.runSomeFunction();
});

問題是,即使實現了函數調用,每次運行self.runSomeFunction()它都會崩潰。 錯誤是

無法識別的選擇器

sent to instance 0x165c7390
2014-07-07 16:23:14.809 pong[3950:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM runSomeFunction]: unrecognized selector sent to instance 0x165c7390'

我知道完成塊工作,因為我可以從它上面顯示NSLog並顯示一些內容,但是嘗試訪問self總是會導致崩潰。

有任何想法嗎? 我不應該試圖訪問自己嗎?

===更新===

主要是我想弄清楚的是如何在Swift閉包中訪問self 它不斷拋出錯誤的訪問錯誤。

這是正在運行的代碼

 func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{
    var cell = tableView.dequeueReusableCellWithIdentifier("userCell") as MCSwipeTableViewCell!

    if !cell {
        cell = MCSwipeTableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "userCell")
     }
    cell.setSwipeGestureWithView(crossView, color: UIColor.colorFromRGB(RED), mode: MCSwipeTableViewCellMode.Switch, state:MCSwipeTableViewCellState.State1, completionBlock: { (cell: MCSwipeTableViewCell!, state: MCSwipeTableViewCellState!, mode: MCSwipeTableViewCellMode!) -> Void in
        self.runSomething();
    });
    return cell
}

 func runSomething()
{
    NSLog("hey there");
}

您可以定義捕獲列表以在Closure中使用self如下所示:

cell.setSwipeGestureWithView(crossView, color: UIColor.colorFromRGB(RED), mode: MCSwipeTableViewCellMode.Switch, state:MCSwipeTableViewCellState.State1) {
    [unowned self]
    cell, state, mode in
    self.runSomething()
}

目前[unowned self]有時會崩潰所以暫時使用[weak self]並在你的封閉內部解開self如: self!.doSomething()

首先,你需要通過以下方式削弱self[weak self] 在內部塊之后嘗試檢查self是否nil

if let weakSelf = self {
   // do whatever you want with the self
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM