當用戶打開該應用時,需要下載存儲MySQL數據庫上的信息,將其保存到核心數據,然後在表視圖控制器顯示它。數據的下載和保存有效,但不會將其呈現給用戶。數據在第一次顯示視圖控制器時不會出現;它僅在切換到不同的視圖並返回之後才呈現。我試圖把它加載在viewWillAppear中的功能數據的代碼(在那裏,我認爲它屬於)和viewDidLoad中的功能 - 無論是用相同的,前面描述的結果。有人能幫我發現我可能做錯了什麼嗎?也許我的語句按錯誤順序執行?初始下載應用數據
另外,我看到另一個奇怪的事情是,當我在調試或使用斷點運行它(又名當我給程序更多的時間來加載),它工作正常。只有在我遇到這些問題時才能正常運行。
查看有沒有加載
override func viewDidLoad() {
/*This is where I would put the code to load the data. See the first
part of viewWillAppear too see what the code is.*/
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector:"viewWillAppear:", name:
UIApplicationWillEnterForegroundNotification, object: nil)
}
查看會出現
override func viewWillAppear(animated: Bool) {
if(!defaults.boolForKey("objectivesDownloaded")) {
downloadObjectives()
defaults.setBool(true, forKey: "objectivesDownloaded")
}
defaults.synchronize()
fetchObjectives()
super.viewWillAppear(animated)
}
獲取目標
func fetchObjectives() {
let fetchRequest = NSFetchRequest(entityName: "Objective")
let sortDescriptor = NSSortDescriptor(key: "logIndex", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
var error: NSError?
let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as [NSManagedObject]?
if var results = fetchedResults {
objectives = results
} else {
println("Could not fetch \(error), \(error?.userInfo)")
}
tableView.reloadData()
}
我假設'downloadObjectives'是一個異步的後臺任務,這意味着當'downloadObjectives'仍在工作時'fetchObjectives'已經被調用。 – zisoft
我無法確認或否認這一點。有沒有,我可以編碼,因此它下載目標,然後加載該視圖?我把代碼下載它在'applicationDidBecomeActive()'或'applicationWillEnterForeground()'函數中的AppDelegate? –