一个接一个地运行一个函数完成

时间:2016-02-12 08:21:30

标签: ios swift

我试图在pullData()完成后运行loadViews(),我想知道这样做的最佳方法是什么?我想在它上面设置10秒超时,如果可能的话我可以显示网络错误。从我所看到的,GCD看起来是实现这一目标的方式,但我对它的实现感到困惑。感谢您提供任何帮助!

//1
pullData()
//2
loadViews()

4 个答案:

答案 0 :(得分:19)

您需要的是具有完成块的完成处理程序。

创建一个非常简单:

func firstTask(completion: (success: Bool) -> Void) {
    // Do something

    // Call completion, when finished, success or faliure
    completion(success: true)
}

然后像这样使用你的完成块:

firstTask { (success) -> Void in
    if success {
       // do second task if success
       secondTask()
    }
}

答案 1 :(得分:2)

我有一种类似的情况,一旦从Parse服务器中提取数据,我就必须初始化一个视图。我使用了以下内容:

func fetchQuestionBank(complete:()->()){

        let userDefault = NSUserDefaults.standardUserDefaults()
        let username = userDefault.valueForKey("user_email") as? String

        var query = PFQuery(className:"QuestionBank")
        query.whereKey("teacher", equalTo: username!)

        query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]?, error:NSError?) -> Void in

            if error == nil {
                if let objects = objects as? [PFObject] {

                    var questionTitle:String?
                    var options:NSArray?

                    for (index, object) in enumerate(objects) {

                        questionTitle = object["question_title"] as? String
                        options = object["options"] as? NSArray
                        var aQuestion = MultipleChoiceQuestion(questionTitle: questionTitle!, options: options!)
                        aQuestion.questionId = object.objectId!
                        InstantlyModel.sharedInstance.questionBank.append(aQuestion)
                    }


                    complete()
                }
            }else{
                println(" Question Bank Error \(error) ")
            }
        }
    }

这就是你所说的方法:

self.fetchQuestionBank({ () -> () in
                        //Once all the data pulled from server. Show Teacher View.
                        self.teacherViewController = TeacherViewController(nibName: "TeacherViewController", bundle: nil)
                        self.view.addSubview(self.teacherViewController!.view)
                    })

答案 2 :(得分:2)

你可以这样做: -

func demo(completion: (success: Bool) -> Void) {
     // code goes here
   completion(success: true)
}

答案 3 :(得分:0)

let quote = ["Celebrate Your Small Wins", "Surround Yourself With Motivated People", "Whatever you are, be a good one", "People who wonder if the glass is half empty or full miss the point. The glass is refillable.", "I’m alive, motivated and ready to slay the day"];

var btn = document.getElementById("btn");

var content = document.getElementById("content");

var i = 0;
btn.addEventListener("click", function() {
  // Display the quote
  content.innerHTML = quote[i];
  // Prepare to shown the next quote
  // Notice quote.length - 1. We must not get value that is equal to `quote.length`
  i = i < quote.length - 1 ? ++i : 0;
});

使用函数!一旦function1()函数完成,就会执行function2()。