随着最近的xcode发布(GM),我在构建我的项目时遇到了很多错误,在以前的版本中没有发现,就像下面的代码
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let sectionInfo = self.fetchedResultsController.sections[section] as NSFetchedResultsSectionInfo
println("numberOfRowsInSection: \(self.entityName()) : \(sectionInfo.numberOfObjects)")
return sectionInfo.numberOfObjects
}我用下面的代码重写了它:
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//#warning Incomplete method implementation -- Return the number of items in the section
if let sectionInfo = fetchedResultsController.sections {
println("numberOfRowsInSection: \(self.entityName()) : \(sectionInfo[section].numberOfObjects)")
return sectionInfo[section].numberOfObjects
}
return 0
}有没有更好更正确的方法来写这篇文章呢?
发布于 2014-09-13 16:37:21
从Xcode6测试版6或7开始,NSFetchedResultsController的sections属性是可选的。因此,苹果现在在Xcode6 GM Master-Detail应用模板中使用以下代码,并激活核心数据(请注意,此代码适用于UITableViews,但它也适用于-collectionView:numberOfItemsInSection:中的UICollectionViews ):
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionInfo = fetchedResultsController.sections![section] as NSFetchedResultsSectionInfo
return sectionInfo.numberOfObjects
}如果您在此方法中放置断点并第一次启动Xcode6 GM Master-Detail应用程序模板,您将看到此方法已被调用,并且sectionInfo有一个值,即使在初始获取请求之后没有要返回的项。
虽然为了更清楚起见,我更倾向于可选绑定,但我猜如果您严格遵循Apple Core数据模式,重用此代码(不执行可选绑定)可能是无害的。无论如何,您的可选绑定代码似乎是正确的。
发布于 2014-09-13 16:25:19
坦率地说,我不是用swift编程的,但我认为这个Obj-C代码片段应该可以帮助你重构你的代码:
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
NSInteger rows = 0;
if ([[self.fetchedResultsController sections] count] > 0) {
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
rows = [sectionInfo numberOfObjects];
}
return rows;
}https://stackoverflow.com/questions/25820496
复制相似问题