简体   繁体   English

NSManagedObject和协议的一致性

[英]NSManagedObject and protocol conformance

Here is my problem, I have an type ( MyManObj ) which is a subclass of NSManagedObject . 这是我的问题,我有一个类型( MyManObj ),它是NSManagedObject的子NSManagedObject

This type has two fields: fieldOne , fieldTwo : Int16 此类型有两个字段: fieldOnefieldTwoInt16

I also have a protocol defined this way: 我也有这样定义的协议:

@objc protocol MyProtocol {
    var fieldOne:Int16 {get set}
    var fieldTwo:Int16 {get set}
}

I need to express the fact that MyManObj conforms to MyProtocol . 我需要表达一个事实,即MyManObj符合MyProtocol And I don't know how to do it. 而且我不知道该怎么做。

I have tried to add code like this, but it does not work: 我试图添加这样的代码,但是它不起作用:

extension MyManObj:MyProtocol {}

Precisely I get this message: 恰好我收到此消息:

Type 'MyManObj' does not conform to protocol 'MyProtocol'.

I have then tried a few more variations, but with no interest because they failed. 然后,我尝试了更多的变体,但没有兴趣,因为它们失败了。

You are getting this error because the variables/ properties in your protocol are not marked optional [ie they are required] and your compiler is asking you to implement all the method/ properties declared in your protocol. 之所以出现此错误,是因为协议中的变量/属性未标记为可选(即它们是必需的),并且编译器要求您实现协议中声明的所有方法/属性。

To resolve this issue you can do: 要解决此问题,您可以执行以下操作:

@objc protocol MyProtocol: class {
     optional var fieldOne:Int16 {get set}
     optional var fieldTwo:Int16 {get set}
 }

OR 要么

extension MyManObj:MyProtocol {
    var fieldOne:Int16 {
        get{}
        set{}
    }
    var fieldTwo:Int16 {
        get{}
        set{}
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM