简体   繁体   中英

Swift ObjectMapper not calling didSet

I'm using ObjectMapper to populate the properties of my Realm object from some JSON. But the didSet doesn't seem to be called whenever the remotePath property is changed by the Mapper .

Here's a trimmed down version of my class (i've just removed a bunch of properties to keep i concise)

class ImageFile: Object, Mappable  {   

    dynamic var id = 0

    dynamic var filename = ""

    dynamic var remotepath = "" {

        didSet {

            self.filename = self.remotepath.isEmpty ? "x" : "z"

        }

    }


    required convenience init?(map: Map) {

        self.init()

    }    

    override static func primaryKey() -> String? {

        return "id"

    }



    func mapping(map: Map) {

        remotepath <- map[“path"]

    }     

}

I'm invoking this like so:

let file = ImageFile()
file.id = json["fileId"].int

// Map the properties
file.mapping(map: Map(mappingType: .fromJSON, JSON: json.dictionaryObject ?? [:]))

I've tried putting a breakpoint inside the didSet as well as a print just to see if it's firing and it isn't/ But if i check the database, I do see the correct value inside the remotepath property, so it's definitely being filled in.

I know that the didSet wont fire during init, but i'm mapping after the init so it should fire? I've checked github issues on ObjectMapper and people have used didSet with ObjectMapper, so i'm obviously missing something...

Any help is greatly appreciated :)

Notes:

  • All of the properties of this object get filled in, except filename one which is supposed to be set inside the didSet callback.
  • There's a reason i chose to not map the ID, just ignore that, provided just for clarity.
  • I've used "x" and "z" as the filename just to test if it's being triggered, just ignore the fact they make no sense, that's not the problem.

Property observers don't work on Realm objects. This is a known limitation of Realm due to the fact that objects exist in the Objective-C runtime (hence the dynamic modifier). See this GitHub issue for more details. You can use Realm s built in notifications as a workaround for property observers.

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