使用Swift Closures。代碼
部件看起來就像是:
DataLoader.swift
class DataLoader: NSObject {
func uploadData(completion: ([AnyObject]) ->()) {
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
let array = [1, 2, 3, 4] //load your data in background thread
dispatch_async(dispatch_get_main_queue()) {
completion(array) //send completion in main thread
}
}
}
}
ViewController.swift
class ViewController: UIViewController {
let dataLoader = DataLoader()
override func viewDidLoad() {
super.viewDidLoad()
self.dataLoader.uploadData {
(any) in
if let movieArray = any as? [Int] { //Here instead of [Int] should be your array of objects e.g. [Movies]
print("result: \(movieArray)")
self.movies = movieArray
self.tableView.reloadData()
}
}
}
}