0

NSKeyedArchiver.archiveRootObject is called but the getter returns variable 'a' as nil. It's annoying me.

Anyone see what the problem is here ?

let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("Information.ab")

var info: Information? {
        get {
            let a = NSKeyedUnarchiver.unarchiveObject(withFile: url.absoluteString) as? Information
            return a
        }
        set {
            if info != newValue && newValue != nil {
                NSKeyedArchiver.archiveRootObject(newValue as Any, toFile: url.absoluteString)
            }
        }
    }

class Information: RecordModel {

    let rules: CKAsset
    let aboutUs: String
    let terms: String
    let privacyPolicy: String

    override init(record: CKRecord) {
        rules = record["rules"] as! CKAsset
        aboutUs = record["aboutUs"] as! String
        terms = record["terms"] as! String
        privacyPolicy = record["privacyPolicy"] as! String
        super.init(record: record)
    }

}

class RecordModel: NSObject, NSCoding {

    let record: CKRecord

    init(record: CKRecord) {
        self.record = record
    }

    required convenience init?(coder aDecoder: NSCoder) {
        let record = aDecoder.decodeObject(forKey: "keyRecord") as! CKRecord
        self.init(record: record)
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(record, forKey: "keyRecord")
    }

    override func isEqual(_ object: Any?) -> Bool {
        if let rhs = object as? Information {
            return record.recordID == rhs.record.recordID
        }
        return false
    }

    override var hash: Int {
        return record.recordID.hashValue
    }

}

1 Answers1

2

Both unarchiveObject(withFile and archiveRootObject(_:toFile expect a file path without the file:// scheme, so it's in both cases

url.path

rather than url.absoluteString

vadian
  • 274,689
  • 30
  • 353
  • 361