将全局变量传递给闭包

时间:2015-06-25 17:16:50

标签: ios swift cocoa-touch xcode6

我正在尝试基于动作表选择实现排序,其中排序发生在处理程序中,但我无法传递我想要排序到处理程序的数组。这是我的代码:

let byWage = UIAlertAction(title: "By Wage", style: UIAlertActionStyle.Default, handler: { action in
  unclaimedJobs.sort() { $0.wage > $1.wage }
})

其中unclaimedJobs是全局变量。最好的方法是什么?

编辑:我在此声明unclaimedJobs

class JobsListViewController: UITableViewController, UITableViewDataSource {

   var jobsList: JobsList!
   var unclaimedJobs: [Job]!

我在viewDidLoad()初始化它。

编辑#2:我知道您需要将UIAlertAction传递给闭包,因此我将(unclaimedJobs)替换为action.

上次修改:我通过将self.unclaimedJobs代替unclaimedJobs.

来解决此问题

2 个答案:

答案 0 :(得分:0)

不是100%肯定。但我认为就是这样。

let byWage = UIAlertAction(title: "By Wage", style: .Default, handler: {(alert: UIAlertAction!) in unclaimedJobs.sort({$0 > $1}) })

答案 1 :(得分:0)

If you refer to an object inside a closure, you need an explicit reference to it. In your case it's probably - self: like in self.unclaimedJobs. However, you have to unown this object like [unowned self] inside the closure, otherwise you'll have a memory leak.