2016-01-22 5 views
0

В настоящее время разрабатывается быстрое приложение с табличным видом, заполненным облачным набором.Содержимое таблицы не будет отображаться до тех пор, пока не будет нажата кнопка экрана.

По какой-то причине, когда приложение открывается, табличное представление отображается пустым, но после того, как экран коснулся, мой список записей неожиданно появляется.

Я представил весь мой мастер-класс Tableview ниже. Мое мышление состоит в том, что это что-то связано с функцией viewDidLoad(), но я не могу понять, что бы я ни старался.

import UIKit 
import CloudKit 
import MobileCoreServices 

class MasterViewController: UITableViewController { 

    //// DB setup (outside DidLoad) 
    let container = CKContainer.defaultContainer() 
    var Database: CKDatabase? 
    var currentRecord: CKRecord? 

    var detailViewController: DetailViewController? = nil 

    ///Array to save dbrecords 
    var objects = [CKRecord]() 

    /// Initialise object of ClipManager class 
    let MyClipManager = ClipManager() 






    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Database loading on runtime 
     Database = container.privateCloudDatabase 

     ///Build Query 
     let query = CKQuery(recordType: "CloudNote", predicate: NSPredicate(format: "TRUEPREDICATE")) 

     ///Perform query on DB 
     Database!.performQuery(query, inZoneWithID: nil) { (records, error) -> Void in 
      if (error != nil) { 
       NSLog("Error performing query. \(error.debugDescription)") 
       return 
      } 

      self.objects = records! 
      self.tableView.reloadData() 
     } 


     // Do any additional setup after loading the view, typically from a nib. 
     self.navigationItem.leftBarButtonItem = self.editButtonItem() 

     let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:") 
     self.navigationItem.rightBarButtonItem = addButton 
     if let split = self.splitViewController { 
      let controllers = split.viewControllers 
      self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController 
     } 
    } 

    override func viewWillAppear(animated: Bool) { 
     self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed 
     super.viewWillAppear(animated) 
    } 




    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 





    // Tableview stuff --- Done 

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
     return 1 
    } 
      /////// Get number of rows 
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return objects.count 
    } 
      //// FIll the table 
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) 

     let object = objects[indexPath.row] 
     cell.textLabel!.text = object.objectForKey("Notes") as? String 
     return cell 
    } 

    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { 
     // Return false if you do not want the specified item to be editable. 
     return true 
    } 
    //// Deleting the table 
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { 
     if editingStyle == .Delete { 

      //DB call working 
      MyClipManager.DeleteMethod(Database!, MyRecord:objects[indexPath.row]) 

      objects.removeAtIndex(indexPath.row) 
      tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) 


     } else if editingStyle == .Insert { 
      // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. 
     } 
    } 


} 

ответ

3

Учитывая, что перезагрузка происходит в обработчике завершения, я предполагаю, что это на фоновом потоке. Попробуйте отправить обновление своего пользовательского интерфейса обратно в основной поток.

(Typing образец без Xcode здесь, так что проверить мой синтаксис.)

Пример:

dispatch_async(dispatch_get_main_queue()) { 
    self.tableView.reloadData() 
} 
+0

Я не слишком уверен, что я понимаю. Как я могу контролировать, какие потоки выбирают, какой бит кода? – Malorrr

+0

GCD - это самый быстрый способ, если вам просто нужно что-то простое. Вот ссылка: https://thatthinginswift.com/background-threads/ –

+0

Работал отлично, Филипп, спасибо! – Malorrr

Смежные вопросы