Vivek Saurav
Vivek Saurav

Reputation: 2275

Xml Serialization/Deserialization of Class in Swift

As being new to Swift

i don't know how to serialize a class into 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 have searched a lot but haven't come across any XML Serialization Engine for Swift.

Upvotes: 5

Views: 4828

Answers (1)

Jiri Trecak
Jiri Trecak

Reputation: 5122

XML Serialization

For XML serialization, I suggest you use following library:

https://github.com/skjolber/xswi

As the usage is quite easy but well documented, I won't copy it here, instead you can just use examples that they provide. Since your class is very easy, it is sufficient solution. AFAIK there is no library that provides automatic serialization, because it is not used on iOS. Core data provide you with option to serialize as XML, but that is highly problematic and mostly not usable for what you want.

NSCoding / NSKeyedArchiver

If you need to just store the class on the disk and load it again, there is better option, and that is to use NSKeyedArchiver / NSCoding protocol. Again, there is great article about how to use it with extensive examples, so just the basics:

  • You extend your class so it conforms to NSCoding protocol
  • You write implementation of two methods - encodeWithCoder: and initWithDecoder:
  • You use NSKeyedArchiver to archive your class
  • You write NSData that you save to disk (and vice versa)

Hope it helps!

Upvotes: 5

Related Questions