I want to display some data in UICollectionView read from Core Data in viewDidLoad. However, when the UICollectionView is presenting its cells, the data has not been fully loaded yet. Thus, the UICollectionView is empty.
What I want to ask is how to make sure the data is ready before the UICollectionView starts to load its cells. Following is part of the code I'm working on.
class MenuViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var categoryCollectionView: UICollectionView!
var allDishes = [AnyObject]()
var categoryList = [String]()
let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let request = NSFetchRequest(entityName: self.dishItemEntityName)
var allDishes = self.context?.executeFetchRequest(request, error: nil)
if let allDishes = allDishes {
for dish in self.allDishes {
let dish = dish as! DishItem
if contains(self.categoryList, dish.category) {
continue
} else {
self.categoryList.append(dish.category)
}
}
}
}
// MARK: Delegate Methods
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.categoryList.count
}
}
viewDidLoad
is called before viewWillAppear
. You could call reloadData
on the collection view in viewWillAppear
.
Better: use a NSFetchedResultsController
which will give many other benefits for memory management, performance and automatic updates.
Call reloadData at the end of viewDidLoad
override func viewDidLoad() {
...
categoryCollectionView.reloadData()
}
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.