如何在Swift 4中为NSFetchedResultsController编写扩展 [英] How to write an extension for NSFetchedResultsController in Swift 4

查看:63
本文介绍了如何在Swift 4中为NSFetchedResultsController编写扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为Swift 4中的NSFetchedResultsController类编写一个简单的扩展.

I'm trying to write a simple extension to the NSFetchedResultsController class in Swift 4.

这是我的第一次尝试-在Swift 3中起作用了

Here's my first attempt - which worked in Swift 3:

public extension NSFetchedResultsController
{
    public func sectionCount() -> Int
    {
        if self.sections == nil
        {
            return 0
        }

        return self.sections!.count
    }
}

但是我在Swift 4的Xcode 9 beta 2中遇到了这个编译错误:

But I get this compile error in Xcode 9 beta 2 with Swift 4:

通用Objective-C类的扩展无法访问该类的 运行时通用参数

Extension of a generic Objective-C class cannot access the class's generic parameters at runtime

我尝试了其他变种但无济于事.注意,我可以创建绑定到与resultType匹配的特定类型NSManagedObject的扩展.但这有一个缺点,即我需要为与NSFetchedResultsController一起使用的每种托管对象类型创建一个扩展.

I've tried other variations to no avail. Note that I can create an extension bound to a specific type of NSManagedObject matching the resultType; but this has the disadvantage that I need to create an extension for every managed object type used with the NSFetchedResultsController.

最新的Swift 4文档似乎不能很好地解释这一点.

The latest Swift 4 docs don't seem to explain this well.

推荐答案

我想我找到了答案. 该功能必须可用于Objective-C.

I think I found the answer to this one. The function needs to be available to Objective-C.

func中添加@objc应该可以消除编译错误.至少对我有用!

Adding @objc to the func should remove the compile error. At least it did for me!

这篇关于如何在Swift 4中为NSFetchedResultsController编写扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆