我正在尝试获取用户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!)
}
}
}
答案 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
}
}
}