从函数swift

时间:2015-11-24 13:41:14

标签: function variables swift2

我正在尝试获取用户ID并将其保存在变量selectedUserID中。 selectedUserID的第一个打印给了我正确的值,但是当我在函数外部进行打印时,我得到一个空值。 这可能是什么问题?

var selectedUserID: String!;

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){

    let indexPath = tableView.indexPathForSelectedRow

    let currentCell = tableView.cellForRowAtIndexPath(indexPath!)! as UITableViewCell

    print("Tableview selection is : " + currentCell.textLabel!.text!)

    selectedUsername = (currentCell.textLabel?.text)


    //Opzoeken wat het bijhorende ID is
    let query = PFQuery(className:"_User")
    query.whereKey("username", equalTo:selectedUsername)
    query.findObjectsInBackgroundWithBlock {
        (objects: [PFObject]?, error: NSError?) -> Void in

            // Do something with the found object

                for object in objects!
                {
                    self.selectedUserID = object.objectId
                    print("the destination is :" + self.selectedUserID!)
                }

    }

}

1 个答案:

答案 0 :(得分:1)

在块外添加任何声明self.selectedUserID的代码将始终返回nil。

您需要从块内调用segue / other视图: (使用segue的例子)

query.findObjectsInBackgroundWithBlock {
        (objects: [PFObject]?, error: NSError?) -> Void in
            // Do something with the found object
            for object in objects! {
                self.selectedUserID = object.objectId
            }

            if selectedUserID == self.selectedUserID {
                self.performSegueWithIdentifier("<yourSegue>", sender: nil)
            } else {
                // Something is wrong
            }

}

然后你需要捕获segue调用,例如:(允许你传递变量)

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
    if segue.identifier == "<yourSegue>" {
        if let viewController: OriginsViewController = segue.destinationViewController as? OriginsViewController {
            viewController.userID = selectedUser
        }
    }
}