Realm with XMLMapper


#1

I’m using XMLMapper with my Realm objects - example class is below…

When testing, if I create a simple, detached Realm object, I am able to call object.toXMLString() and it will give me back the XML representation of the object.

However, once I add the object to a realm, any attempt to call object.toXMLString() results in

failed: caught “RLMException”, “Primary key can’t be changed after an object is inserted.”

I’ve tried to then create a “detached copy” of the object like so:

let foo = ICRealmPolyStyle(value: existingObject)

but if I call foo.toXMLString(), I get the same exception - even though this “should” be a detached copy…

  1. Why is simply calling toXMLString() trying to change the existing object? (I know that this is not the XMLMapper forum, but I am hoping someone may know).

  2. Is there a way I can create an actual “detached” copy of an object so that I can dump the XML?

Thanks.

@objcMembers public class ICRealmPolyStyle: Object, XMLMappable {
    enum Property: String {
        case color, outline, fill, eventUID
    }
    
    dynamic var eventUID: String = ""
    
    // Primary key
    override public static func primaryKey() -> String? {
        return Property.eventUID.rawValue
    }
    
    dynamic var color: String? = ""
    dynamic var outline: Bool  = false
    dynamic var fill: Bool     = false
    
    convenience init(color: String = "", outline: Bool = false, fill: Bool = false) {
        self.init()
        
        self.color   = color
        self.outline = outline
        self.fill    = fill
    }
    

    // XMLMappable
    public var nodeName: String!
    
    // Properties for Realm to ignore
    override public static func ignoredProperties() -> [String] {
        return ["nodeName"]
    }
    
    required convenience public init?(map: XMLMap) {
        self.init()
    }
    
    public func mapping(map: XMLMap) {
        color   <- map["color"]
        outline <- map["outline"]
        fill    <- map["fill"]
    }
    // XMLMappable
    
    
    // MARK: - Conform to CustomDebugStringConvertible
    override public var debugDescription: String {
        var outputString = lineWith(separator: "…", title: "ICRealmPolyStyle")
        outputString.append("Color: \(String(describing: color))\n")
        outputString.append("Outline: \(String(describing: outline))")
        outputString.append("Fill: \(String(describing: fill))")
        outputString.append(lineWith(separator: "…", title: "ICRealmPolyStyle"))
        return outputString
    }
}

#2

I’m making progress and this was probably the wrong forum to post this. Sorry.