lalala lalala - 1 year ago 90
Swift Question

Save NSArray of Class to cacheDirectory

I'd like to NSArray of Class to the cacheDirectory. I've wrote as following, however it returns false. Could you tell me how to solve this problem? Thank you for your kindness.

let paths2 = NSSearchPathForDirectoriesInDomains(
.UserDomainMask, true)
let cachesPath: AnyObject = paths2[0]

var cachedQuestions:NSArray = questions as NSArray
let filePath = cachesPath.stringByAppendingPathComponent("CachedQuestions")

class Dog {
var id:Int?
var name:String?
init(id:Int, name:String) { = id = name

var dogs = [Dog]()
dogs.append(Dog(id:1, name:"taro"))
dogs.append(Dog(id:2, name:"jiro"))
var nsArrayDogs:NSArray = dogs as NSArray

let success = nsArrayDogs.writeToFile(filePath, atomically: true)

if success {
println("save success")

Answer Source

Xcode 7.3.1 • Swift 2.2.1

You can make your Dog class NSCoding compliant:

class Dog: NSObject, NSCoding {
    let id: Int
    let name: String
    required init(id: Int, name: String) { = id = name
    required init(coder decoder: NSCoder){ = decoder.decodeObjectForKey("id") as? Int ?? 0 = decoder.decodeObjectForKey("name") as? String ?? ""
    func encodeWithCoder(coder: NSCoder) {
        coder.encodeObject(id, forKey: "id")
        coder.encodeObject(name, forKey: "name")

Then you can save your array data to disk as follow:

class ViewController: UIViewController {

    override func viewDidLoad() {
        // Do any additional setup after loading the view, typically from a nib.
        let dog1 = Dog(id: 1, name: "taro")
        let dog2 = Dog(id: 2, name: "jiro")
        do {
            let cachesDirectoryURL = try NSFileManager.defaultManager().URLForDirectory(.CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
            let array = [dog1, dog2]
            let fileURL = cachesDirectoryURL.URLByAppendingPathComponent("CachedQuestions.plist")
            let success = NSKeyedArchiver.archiveRootObject(array, toFile: fileURL.path!)
            // to load it from disk
            if let loadedArray = NSKeyedUnarchiver.unarchiveObjectWithFile(fileURL.path!) as? [Dog] {
                print(loadedArray.count)   // 2
        } catch let error as NSError {
    override func didReceiveMemoryWarning() {
        // Dispose of any resources that can be recreated.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download