Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property cannot be marked @objc because its type cannot be represented in Objective-C

I'm finishing a port for a project that was written in Swift to support Objective-C. A lot of the project was written to support Objective-C but not the properties on a particular class.

This is the property:

open var remainingTime: ( hours: Int, minutes: Int, seconds: Int)?

I'm guessing I can't just add @objc to this because "hours","minutes","seconds" are objects. How do I make this property visible to my Objective-C project?

like image 468
CokePokes Avatar asked Sep 20 '18 05:09

CokePokes


1 Answers

This error occurred in project when I tried to observe an Enum via KVO. My enum looked like this:

enum EnumName: String {
    case one = "One"
    case two = "Two"
}

In case you are struggling to observe it, this workaround helped solve my issue.

Observable Class:

  • create @objc dynamic var observable: String?
  • create your enum instance like this:

    private var _enumName: EnumName? {
        didSet {
            observable = _enumName!.rawValue
        }
    }
    

Observer Class:

  • create private var _enumName: EnumName?
  • create private let _instance = ObservableClass()
  • create

    private var _enumObserver: NSKeyValueObservation = _instance.observe(\.observable, options: .new, changeHandler: { [weak self] (_, value) in
        guard let newValue = value.newValue else { return }
        self?._enumName = EnumName(rawValue: period)!
    })
    

Than's it. Now each time you change the _enumName in the observable class, an appropriate instance on the observer class will be immediately updated as well.

This is of course an oversimplified implementation, but it should give you an idea of how to observe KVO-incompatible properties.

like image 161
Gasper J. Avatar answered Sep 17 '22 23:09

Gasper J.