Swift NSCoding - 如何读取编码数组

时间:2017-01-07 08:30:07

标签: arrays nscoding nskeyedunarchiver

我正在使用Swift playground使用NSCoding编写父子关系。

这种关系可以描述为:

  

一个 int[] array = { 3, 7, 9, 7, 4, 9, 7, 9 }; int length = array.Length; int Maxvalue = array.Max(); int[] FrequentArray = new int[Maxvalue + 1]; for (int i = 0; i < length; i++) { FrequentArray[array[i]]++; } for (int i = 0; i < Maxvalue + 1; i++) { if (FrequentArray[i] > 2) { Console.WriteLine(i); } } 可以写出许多Author

但是,当我尝试保存图书集时,它会导致错误;

  

游乐场执行中止:错误:执行被中断,   原因:EXC_BAD_INSTRUCTION(代码= EXC_I386_INVOP,子代码= 0x0)。该   进程已被中断,使用   “thread return -x”返回表达式之前的状态   评价。

我的Swift游乐场代码如下;

Books

所以我的问题是:导致错误的原因是什么?如何纠正这个问题?

非常感谢

1 个答案:

答案 0 :(得分:1)

我能够通过重构我的代码来解决这个问题。

class Author: NSObject, NSCoding
{
    var name: String
    var books:[Book] = [Book]()

    init(name:String, books:[Book]?) {
        self.name = name
        guard let bookList = books else {
            return
        }
        self.books = bookList
    }

    required convenience init?(coder aDecoder: NSCoder) {
        let name = aDecoder.decodeObject(forKey:"name") as! String
        let books = aDecoder.decodeObject(forKey:"books") as! [Book]

        self.init(name:name, books:books)
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(name, forKey:"name")
        aCoder.encode(books, forKey:"books")
    }

}

class Book: NSObject, NSCoding {
    var title: String
    var author: Author

    init(title:String, author: Author) {
        self.title = title
        self.author = author
    }

    public convenience required init?(coder aDecoder: NSCoder) {

        let title = aDecoder.decodeObject(forKey: "title") as! String
        let author = aDecoder.decodeObject(forKey: "author") as! Author

        self.init(title:title, author:author)
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(title, forKey: "title")
        aCoder.encode(author, forKey: "author")
    }
}

let author:Author = Author(name: "Tom Clancy", books: nil)
let books = [
    Book(title: "The Hunt for Red October", author: author)
    , Book(title: "Red Storm Rising", author: author)
]
//author.books.append(contentsOf: books)


// -----------
// Save data


let manager = FileManager.default
let url = manager.urls(for: .documentDirectory, in: .userDomainMask).first! as URL
let writeFile: URL = url.appendingPathComponent("books.data")

print ("Attempting to write to: \(writeFile.path)")

NSKeyedArchiver.archiveRootObject(books, toFile: writeFile.path)

if let bookData = NSKeyedUnarchiver.unarchiveObject(withFile: writeFile.path) as? [Book] {
    for book in bookData {
        print ("\(book.title) - \(book.author.name)")
    }
}

这似乎有效。

问题已关闭