Xml Serialize / Deserialize a Class in Swift

As new to Swift

I don't know how to serialize a class in xml

Class Employee
{
    var mName : String = ""
    var Name : String
        {
        get
        {
            return mName
        }
        set
        {
            mName = newValue
        }
    }
    var mDesingation : String = ""
    var Desingation: String
        {
        get
        {
            return mDesingation 
        }
        set
        {
            mDesingation = newValue
        }
    }

}

      

I searched a lot but couldn't find any XML Serialization mechanism for Swift.

+3


source to share


1 answer


XML Serialization

For XML serialization, I suggest you use the following library:

https://github.com/skjolber/xswi

Since the usage is quite simple, but well documented, I won't copy it here, you can instead just use the examples they provide. Since your class is very simple, a solution is sufficient. AFAIK there is no library that provides automatic serialization because it is not used in iOS. Core data gives you the ability to serialize to XML, but this is very problematic and mostly not used for what you want.



NSCoding / NSKeyedArchiver

If you just need to save the class to disk and load it again, there is a better option and it should use the NSKeyedArchiver

/ protocol NSCoding

. Again, there is a great article on how to use it with extensive examples, so just the basics:

  • You are extending your class to conform to the protocol NSCoding

  • You are writing an implementation of two methods - encodeWithCoder:

    andinitWithDecoder:

  • You use NSKeyedArchiver

    to archive your class
  • You write NSData

    which you save to disk (and vice versa)

Hope it helps!

+5


source







All Articles