添加对象后更新tableview

时间:2016-06-30 20:09:06

标签: swift

我使用coredata保存字符串,并且所有保存的字符串将在tableview中显示为labeltext。字符串来自alertview中的文本字段。它正确地保存了字符串,但是我必须在表视图中显示新字符串之前再次关闭并运行项目。

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet var tableView: UITableView!

var buyingList : [BuyList] = []

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    gettingData()


    self.tableView.dataSource = self
    self.tableView.delegate = self

}


func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.buyingList.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
   // let Cell = tableView.dequeueReusableCellWithIdentifier("identifier") as UITableViewCell!
    let Cell = UITableViewCell()



    let tableViewData = self.buyingList.reverse()[indexPath.row]
    Cell.textLabel?.text = tableViewData.buyList

    return Cell
}

func refresh(){
    dispatch_async(dispatch_get_main_queue()) { () -> Void in
        dump(self.buyingList)
        self.tableView.reloadData()
    }
}

@IBAction func addButton(sender: UIBarButtonItem) {
    nameOfPicture()
}

func nameOfPicture() {
    let alert = UIAlertController(title: "Tilføj", message: "", preferredStyle: UIAlertControllerStyle.Alert)

    let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)
    alert.addAction(cancel)

    alert.addTextFieldWithConfigurationHandler { (textField) -> Void in

    }

    alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in

        let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

        let savingData = NSEntityDescription.insertNewObjectForEntityForName("BuyList", inManagedObjectContext: context) as! BuyList

        let textf = alert.textFields![0] as UITextField

        savingData.buyList = textf.text

        do {
            try context.save()

        } catch _ {

        }

    }))

    self.presentViewController(alert, animated: true, completion: nil)
}

func gettingData() {
    let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

    let request = NSFetchRequest(entityName: "BuyList")

    var results : [AnyObject]?

    do {
        results = try context.executeFetchRequest(request)
    } catch _ {
        results = nil
    }

    if results != nil {
        self.buyingList = results! as! [BuyList]
    }
}
}

1 个答案:

答案 0 :(得分:1)

获取数据后,不会重新加载tableview。您获取数据的功能应如下所示:

if results != nil {
   self.buyingList = results! as! [BuyList]
   self.tableView.reloadData()
}

如果在此次通话后它没有在您的表格中显示数据,则表示您的结果错误,您的buyList为空