我正在尝试将Parse Class“Conversation”objectId传递给另一个View Controller。当我检查数据没有传递给我指向的变量。
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object(s) to the new view controller.
let selectedIndex = self.tableView.indexPathForSelectedRow()?.row
let destinationVC = segue.destinationViewController as ConversationViewController
//Save Conversation Data
var convo = PFObject(className: "Conversation")
convo.saveInBackgroundWithBlock{
(success: Bool!, error: NSError!) -> Void in
if (success != nil) {
//Save Selected Person
participant["conversationId"] = convo.objectId as String!
participant.saveInBackground()
}
else{
NSLog("%@", error)
}
}
//Trying to Pass convo.objectId
destinationVC.newConversationId = convo.objectId as String!
}
答案 0 :(得分:0)
代码的问题是convo.objectId
未设置在您使用它的位置。它在saveInBackgroundWithBlock:
的完成块中设置,但该块在显示在其下方的代码之后运行。
那该怎么办?如果下一个vc需要在运行之前保存convo对象,那么正确的模式是在保存后运行segue。在代码中找到启动segue的位置,并将其替换为convo.saveInBackgroundWithBlock
。然后从该块中执行performSegue
。
编辑 - 以下是在Objective-C中执行此操作的方法。在任何一种语言中,为了做到这一点,你必须从代码中启动segue。假设你有从IB(或故事板)中的表格视图单元格绘制到下一个视图控制器的segue。删除该segue,然后从包含表的视图控制器开始控制拖动一个新的。 (在IB中选择视图控制器并从那里拖动。然后,使用属性检查器,给出该segue和标识符,例如“ConvoSegue”)。
// since a table selection that starts the action, implement the selection delegate method
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// we decide here that the convo object must be saved, and
// a segue should happen to another vc that needs the convo object:
var convo = PFObject(className: "Conversation")
convo saveInBackgroundWithBlock:^(BOOL success, NSError *error) {
if (!error) {
// now that convo is saved, we can start the segue
[self performSegueWithIdentifier:@"ConvoSegue" sender:convo];
} else {
// don't segue, stay here and deal with the error
}
}];
}
注意上面,我们通过convo作为segue的发送者。这允许在prepareForSegue
中访问它。如果convo是此视图控制器的属性,则可以跳过此步骤。
现在准备看起来像你的segue,除非没有asynch保存......
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
// we don't need the selected row from the table view, because we have
// the convo object as the sender
// let selectedIndex = self.tableView.indexPathForSelectedRow()?.row
let destinationVC = segue.destinationViewController as ConversationViewController
// sorry, back to objective-c here:
PFObject *convo = (PFObject)AnyObject; // need a cast to use properly in objective-c
// deleted your save logic. just pass convo's id
//Trying to Pass convo.objectId
destinationVC.newConversationId = convo.objectId as String!
}