简体   繁体   中英

How to reload tableview after adding new entry?

I am creating a cloudkit tableview. I load the app and my tableview appears with my entries from cloud kit.

I then use my add method insertNewObject which adds the record to cloud kit but this does not show up in my tableview. It will only show up on my next run of the app.

   func insertNewObject(sender: AnyObject) {

    let record = CKRecord(recordType: "CloudNote")
    record.setObject("New Note", forKey: "Notes")

    MyClipManager.SaveMethod(Database!, myRecord:record)
    dispatch_async(dispatch_get_main_queue()) {
        self.tableView.reloadData()
    }


    }

This is my add method. I am calling tableview reload as you can see but nothing is happening.

My tableview creation code:

    // 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
}

As requested: Method that saves to CloudDB

   func SaveMethod(publicDatabase: CKDatabase, myRecord: CKRecord ) -> CKRecord {

    publicDatabase.saveRecord(myRecord, completionHandler:
        ({returnRecord, error in
            if let err = error {
                self.notifyUser("Save Error", message:
                    err.localizedDescription)
            } else {
                dispatch_async(dispatch_get_main_queue()) {
                    self.notifyUser("Success",
                        message: "Record saved successfully")
                }


            }
        }))
 return myRecord
}

My viewdidload method in masterview:

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!

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

        }

You should not reload your entire tableView when you insert a single object. Only do that when you know ALL the data has changed.

To do what you want, this is the order:

    • Insert a new data object into your datasource (self.objects). Make sure you get the index of where it ends up in the array.
    • Call insertRowAtIndexPath: with the correct indexPath on your tableView. This will make sure your data and tableView are in sync again, and tableView:cellForRowAtIndexPath: is called for at least your new data object (and possible others, as certain cells might now be reused to display other data).

Note that the order is always: update your data first, then update your UI (the only place I know of that his is hairy is when using a UISwitch).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM