如何在所有其他代码完成后运行代码?

时间:2015-08-04 16:32:42

标签: ios swift

有点愚蠢的问题,写了一个完整的应用程序,但仍然不知道这个...... 现在我有一个"删除帐户按钮"删除所有用户的帖子并执行segue回登录屏幕,但似乎并非所有帖子都被删除,因为它在完成之前执行segue。

有没有办法只有在删除用户的帖子后才能执行segue?如同,运行segue LAST。

func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
    if buttonIndex == 1 { // Post One Pic
        //self.performSegueWithIdentifier("postimage1segue", sender: self)
        var query = PFQuery(className: "Post")
        query.whereKey("userId", equalTo: PFUser.currentUser()!.objectId!)
        query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
            if let objects = objects {
                for object in objects {
                    PFObject.deleteAllInBackground(objects)
                }
            }
        })

        var query1 = PFQuery(className: "PrivatePost")
        query1.whereKey("userId", equalTo: PFUser.currentUser()!.objectId!)
        query1.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
            if let objects = objects {
                for object in objects {
                    PFObject.deleteAllInBackground(objects)
                }
            }
        })

        PFUser.currentUser().deleteInBackground()
        performSegueWithIdentifier("accountdeletedsegue", sender: self)
    }
}

1 个答案:

答案 0 :(得分:0)

我不确定PFUser是否有deleteInBackgroundWithBlock:方法,但你也可以使用Grand Central Dispatch。

以下是Obj-C中的一个例子:

dispatch_group_t group = dispatch_group_create();
dispatch_queue_t bg_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_group_async(group, bg_queue, ^{
    // do something 
});

dispatch_group_notify(group, dispatch_get_main_queue(), ^{
    //when done do something else on main
});

编辑:Swift GCD小组

var downloadGroup = dispatch_group_create()
dispatch_group_enter(group)

// Do something

dispatch_group_leave(group)

dispatch_group_notify(group, GlobalMainQueue) {
    //when something is done do something else on main queue
}