繁体   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