简体   繁体   中英

swift - coredata refresh tableview

I have a tableview to display product, and a view to add a new product.

In AddProductViewController, after adding product data to coredata I dismiss the controller and return to my ProductTableView.

navigationController!.popViewControllerAnimated(true)

In ProductTableView I added 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()
    }

What I have is:
1. Tableview is not refreshed after dismissing the second viewcontroller
2. There is a frozen refresh icon.
3. when I launch my app, I have a refresh wheel spinning and not disappearing.

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()
}

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