【问题标题】:getting a value inside a code block to function return in swift在代码块中获取一个值以快速返回函数
【发布时间】:2015-09-27 14:31:46
【问题描述】:

我正在使用解析,我正在尝试返回表的 row.count 并将其输出到 label.text。

func numberOfPostedJobsCount() -> Int{
    var postsCount: Int?
    var query = PFQuery(className: "Post")
    if let user = PFUser.currentUser() {
        query.whereKey("user", equalTo: user)
    }
    query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]?, error) -> Void in
        if error == nil {
            //query succeeded
            print("\(objects?.count)")
        } else {
            print("\(error)")
        }
    }

    return postsCount!
}

viewDidLoad()里面的代码是

numberOfPostedJobs.text = String(numberOfPostedJobsCount())

错误:致命错误:在展开可选值时意外发现 nil

编辑 1:我尝试添加公共或私有变量,但没有奏效。

func numberOfPostedJobsCount() -> (Int) {
    var num1: Int = 0
    var query = PFQuery(className: "Post")
    if let user = PFUser.currentUser() {
        query.whereKey("user", equalTo: user)
    }
    query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]?, error) -> Void in

        if error == nil {
            //query succeeded
            print("\(objects?.count)")
            num1 = (objects?.count)!
            print(num1)
        } else {
            print("\(error)")
        }
    }

    return num1
}

【问题讨论】:

    标签: parse-platform swift2


    【解决方案1】:

    原因是postsCount被声明但从未被初始化,所以当你打开它时它是nil

    请注意,函数findObjectsInBackgroundWithBlock 是异步工作的,这意味着该块总是返回语句之后调用。在此块中,您必须更新数据源和/或 UI。

    编辑:

    从您的函数中返回 Void 并使用完成处理程序,例如

    func numberOfPostedJobsCount(completion: (Int) -> ()) {
      var query = PFQuery(className: "Post")
      if let user = PFUser.currentUser() {
        query.whereKey("user", equalTo: user)
      }
      query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]?, error) -> Void in
    
        if error == nil {
          //query succeeded
          print("\(objects?.count)")
          let num1 = (objects?.count)!
          completion(num1)
        } else {
          print("\(error)")
           completion(0)
        }
      }
    }
    

    你这样调用函数

    numberOfPostedJobsCount() { (postsCount) -> () in
      numberOfPostedJobs.text = String(postsCount)
    }
    

    【讨论】:

    • 我在函数内部添加了一个变量作为数据源进行更新。还是不行。我更新了我的帖子
    • 由于块的异步行为,该函数将始终返回 0。
    • 谢谢!我应该更多地了解具有完成功能的功能。效果很好!
    • 如何在另一个函数中调用这个函数?我需要将值返回给 tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    • numberOfRowsInSection 应该返回数组中直接调用<array>.count 的元素数。更新数组并调用reloadData()
    【解决方案2】:

    您可以使用信号量使异步方法同步工作:

    问题陈述的示例方法

    func test()->Int {
        var postsCount: Int?
        let sema:dispatch_semaphore_t = dispatch_semaphore_create(0)
    
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { () -> Void in
            postsCount = 100
            dispatch_semaphore_signal(sema)
        }
    
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER)
        return postsCount!
    }
    

    以上代码:

    func numberOfPostedJobsCount() -> Int{
    var postsCount: Int?
    var query = PFQuery(className: "Post")
    let sema:dispatch_semaphore_t = dispatch_semaphore_create(0)
    if let user = PFUser.currentUser() {
        query.whereKey("user", equalTo: user)
    }
    query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]?, error) -> Void in
        if error == nil {
            //query succeeded
            postsCount = objects?.count
            dispatch_semaphore_signal(sema)
            print("\(objects?.count)")
        } else {
            postsCount = 0
            dispatch_semaphore_signal(sema)
            print("\(error)")
        }
    }
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER)
    return postsCount!
    }
    

    【讨论】:

    • 如何在我的代码中实现这一点,我尝试将 findObject 块放入 dispatch_async 块中。
    • 我试过你的方法,但是当我在 viewDidLoad() 中调用函数时,它的应用程序卡住了
    猜你喜欢
    • 2015-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-19
    • 2015-06-29
    • 2021-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多