在Objective-C框架中使用Swift闭包
我正在使用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()
也会崩溃。 错误是
无法识别的select器
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从它,它显示的东西,但尝试访问自我总是导致崩溃。
有任何想法吗? 我不应该试图访问自己吗?
===更新===
主要是我想弄清楚如何在Swift中closures自己。 它不断抛出一个错误的访问错误。
这是正在运行的代码
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"); }
你可以定义一个捕获列表来使用像这样的闭包:
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()
。
首先,你需要通过: [weak self]
。 并在内部块后尝试检查self
是不是nil
:
if let weakSelf = self { // do whatever you want with the self }