xcode 6 GM - NSFetchedResultsSectionInfo

时间:2014-09-13 06:32:15

标签: swift xcode6 nsfetchedresultscontroller

上一个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
}

有没有更好更正确的方法来写这个?

2 个答案:

答案 0 :(得分:1)

自Xcode 6 beta 6或7以来,NSFetchedResultsController' sections属性是可选的。因此,Apple现在在激活了核心数据的Xcode 6 GM Master-Detail应用程序模板中使用以下代码(请注意,此代码适用于UITableViews,但它也应该应用于UICollectionViews中的-collectionView:numberOfItemsInSection: }):

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let sectionInfo = fetchedResultsController.sections![section] as NSFetchedResultsSectionInfo
    return sectionInfo.numberOfObjects
}

如果您在此方法中放置断点并首次启动Xcode 6 GM Master-Detail应用程序模板,您将看到调用此方法并且sectionInfo具有值,即使存在初始获取请求后没有要返回的项目。

虽然我更喜欢可选绑定,但我想如果您严格遵循Apple Core Data模式,重用此代码可能没有坏处(不进行可选绑定)。无论如何,您的可选绑定代码似乎是正确的。

答案 1 :(得分:0)

坦率地说,我不是快速编程,但我认为这个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;
}