swift - coredata刷新tableview

时间:2015-11-04 08:36:14

标签: ios swift uitableview core-data

我有一个用于显示产品的tableview,以及一个用于添加新产品的视图。

在AddProductViewController中,将产品数据添加到coredata后,我解除了控制器并返回到我的ProductTableView。

navigationController!.popViewControllerAnimated(true)

在ProductTableView中我添加了refreshcontroller

    override func viewDidLoad() {
            super.viewDidLoad()
            product = fetchProducts()
            refreshControl = UIRefreshControl()
            refreshControl?.addTarget(self, action: "refreshProducts", forControlEvents: UIControlEvents.ValueChanged)
            refreshControl?.beginRefreshing()
    }

    func refreshProducts(){
            product = fetchProducts()
    }

    func fetchProducts() -> [Product] {
            let request = NSFetchRequest(entityName: "Product")

            let sortDescriptor = NSSortDescriptor(key: "productName", ascending: true)
            request.sortDescriptors = [sortDescriptor]

            let product = (try! context!.executeFetchRequest(request)) as! [Product]

            self.view.hideLoading()
            self.refreshControl?.endRefreshing()

            return product
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.refreshControl?.beginRefreshing()
        self.tableView.reloadData()
    }

我拥有的是:
 1.解除第二个视图控制器后,表格视图不会刷新  2.有一个冻结的刷新图标  3.当我启动我的应用程序时,我有一个刷新轮旋转而不会消失。

1 个答案:

答案 0 :(得分:1)

override func viewDidLoad() {
        super.viewDidLoad()
        refreshControl = UIRefreshControl()
        refreshControl?.addTarget(self, action: "refreshProducts", forControlEvents: UIControlEvents.ValueChanged)
}

func refreshProducts(){
        product = fetchProducts()
        self.tableView.reloadData()
}

func fetchProducts() -> [Product] {
        let request = NSFetchRequest(entityName: "Product")

        let sortDescriptor = NSSortDescriptor(key: "productName", ascending: true)
        request.sortDescriptors = [sortDescriptor]

        let product = (try! context!.executeFetchRequest(request)) as! [Product]

        self.view.hideLoading()
        self.refreshControl?.endRefreshing()

        return product
}

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    self.refreshControl?.beginRefreshing()
    refreshProducts()
}