ios – 将类的NSArray保存到cacheDirectory

前端之家收集整理的这篇文章主要介绍了ios – 将类的NSArray保存到cacheDirectory前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想将类的NSArray放到cacheDirectory中.我写了如下,但它返回false.你能告诉我如何解决这个问题吗?谢谢你的好意.
let paths2 = NSSearchPathForDirectoriesInDomains(
        .CachesDirectory,.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) {
            self.id = id
            self.name = 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")
    }

解决方法

Xcode 7.3.1•Swift 2.2.1

您可以使您的Dog class NSCoding兼容:

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

然后,您可以将阵列数据保存到磁盘,如下所示:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.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!)
            print(success)
            // to load it from disk
            if let loadedArray = NSKeyedUnarchiver.unarchiveObjectWithFile(fileURL.path!) as? [Dog] {
                print(loadedArray.count)   // 2
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

猜你在找的iOS相关文章