简体   繁体   中英

NSManagedObject and protocol conformance

Here is my problem, I have an type ( MyManObj ) which is a subclass of NSManagedObject .

This type has two fields: fieldOne , fieldTwo : Int16

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 . 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{}
    }
}

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.

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