我正在尝试在创建解析类"对话"对象ID后将其传递给另一个视图控制器。当我检查数据时,数据没有传递给我指向的变量。
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!
}
代码的问题在于convo.objectId
没有在使用它时设置。 它被设置在 saveInBackgroundWithBlock:
的完成块中,但该块在它下面出现的代码之后运行。
那怎么办? 如果下一个 vc 需要在运行之前保存 convo 对象,则正确的模式是在保存后运行 segue。 在代码中找到启动 segue 的点,并将其替换为 convo.saveInBackgroundWithBlock
。 然后从该块内执行performSegue
。
编辑 - 这是在objective-C中执行此操作的方式。 无论使用哪种语言,为了执行此操作,您必须从代码启动 segue。 假设您将 segue 从 IB(或情节提要)中的表视图单元格绘制到下一个视图控制器。 删除该 segue,然后从包含表的视图控制器开始按住 Control 键拖动一个新 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 看起来像你的,除了没有异步保存......
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!
}