2014-12-25 61 views
0

當用戶打開該應用時,需要下載存儲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() 
} 
+0

我假設'downloadObjectives'是一個異步的後臺任務,這意味着當'downloadObjectives'仍在工作時'fetchObjectives'已經被調用。 – zisoft

+0

我無法確認或否認這一點。有沒有,我可以編碼,因此它下載目標,然後加載該視圖?我把代碼下載它在'applicationDidBecomeActive()'或'applicationWillEnterForeground()'函數中的AppDelegate? –

回答

0

用戶必須看到主視圖之前登錄

即,所以我在登錄腳本中找到登錄成功後,但在視圖控制器出現之前,將下載代碼添加到登錄腳本中。數據現在顯示在開始。

if(loginSucceeded) { 
    self.downloadObjectives() 
    self.defaults.setBool(true, forKey: "objectivesDownloaded") 
    let tabBarController = self.storyboard!.instantiateViewControllerWithIdentifier("tabBarController") as UIViewController 
    dispatch_async(dispatch_get_main_queue(), {() -> Void in 
     self.presentViewController(tabBarController, animated: true, completion: nil) 
    }) 
} 
2

你可能不告訴你,你的表獲取數據後重新加載數據。 (它最初將沒有數據加載時視圖負載)的OBJ-C

[yourTable reloadData] 

迅速

yourTable.reloadData() 
+0

所以,我刪除了應用程序,並重新啓動這一點,它仍然沒有下載目標的時候了。我已經包含了'tableView.reloadData()'。還有其他建議嗎? –