how do I serialise NSDictionary from a Class - Swift implementation

会有一股神秘感。 提交于 2019-12-04 06:18:45
Sulthan

In Swift you never work with classes. You work with types:

var clazz: AnyClass? = self.dynamicType
class_copyPropertyList(clazz, nil)

All Obj-C methods that return a Class, e.g. classForCoder are updated to return a Swift type instead (AnyClass).

Note that you have other type problems there:

var propertiesCount : CUnsignedInt = 0
let propertiesInAClass : UnsafePointer<objc_property_t> = class_copyPropertyList(clazz, &propertiesCount)

If you actually need to access the Obj-C class as AnyObject, for example to create an array of classes and pass it to Obj-C, see this

This is how I implemented deep serialization.

If property is DictionarySerializedObject then it's recursively serialized.

Be careful because class_copyPropertyList() does not return properties of optional Swift types like Bool?, [String?] because Foundation does not provide bridges for them. For example it provides bridge for Bool to NSNumber but does not provide bridge for Bool?.

import Foundation

protocol DictionarySerializable {
    func serializeToDictionary() -> [String:AnyObject]
}

class DictionarySerializableObject: NSObject {
}

extension NSObject: DictionarySerializable {
    func serializeToDictionary() -> [String:AnyObject] {
        var aClass: AnyClass? = self.dynamicType
        var propertiesCount: CUnsignedInt = 0
        let properties = class_copyPropertyList(aClass, &propertiesCount)
        var dictionary = [String: AnyObject]()
        for var i = 0; i < Int(propertiesCount); i++ {
            if let name = NSString(CString: property_getName(properties[i]), encoding: NSUTF8StringEncoding) as? String {
                dictionary[name] = getDictionaryValueForObject(self.valueForKey(name))
            }
        }
        free(properties)
        return dictionary
    }

    private func getDictionaryValueForObject(object: AnyObject?) -> AnyObject {
        if let object: AnyObject = object {
            if let object = object as? DictionarySerializableObject {
                return object.serializeToDictionary()
            } else if let object = object as? [AnyObject] {
                var array = [AnyObject]()
                for item in object {
                    array.append(getDictionaryValueForObject(item))
                }
                return array
            } else if let object = object as? NSData {
                return object.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(0))
            } else {
                return object
            }
        } else {
            return NSNull()
        }
    }
}

I'm using this way archiving anything which conforms the NSCoding protocol.

first I get the URL for the folder, like e.g. Documents folder:

var error: NSError?
let documentURL : NSURL = NSFileManager.defaultManager().URLForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomain: NSSearchPathDomainMask.UserDomainMask, appropriateForURL: nil, create: true, error: &error)

then I archive it into that folder:

let object: AnyObject = // ...
let filename: String = "<filename>"
let customExtension: String = "<extension>"
let urlForFile: NSURL = documentURL.URLByAppendingPathComponent(filename).URLByAppendingPathExtension(customExtension)
let result: Bool = NSKeyedArchiver.archivedDataWithRootObject(object).writeToURL(urlForFile, atomically: true)

and unarchiving later is quite similar to the recent way:

let data: NSData = NSData.dataWithContentsOfFile(urlForFile.path, options: NSDataReadingOptions.DataReadingUncached, error: &error)
let object: AnyObject = NSKeyedUnarchiver.unarchiveObjectWithData(data)

NOTE: that is a raw example, without checking anything whether or not it is nil or handling the possible error. you may need to add those for your final code.

I have written an objective c library that automatically does this based on key values and property names. I have a branch to support Swift classes and it works well. https://github.com/aryaxt/OCMapper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!