将数组保存到可以重新加载的文件的最佳方法是什么
What is the best way to save an array to a file that can be reloaded
类似于游戏允许您保存进度的方式,我在 iOS 中有一个应用程序将用户的进度存储在一个数组中。我想将该数组存储到一个文件中,以便当用户重新打开他们的应用程序时,该文件会加载他们的当前状态。
最简单的方法是使用 NSKeyedArchiver
/NSKeyedUnarchiver
对并确保数组中的每个对象都符合 NSCoding
。您可以阅读 here。
NSKeyedArchiver.archiveRootObject(myArray, toFile: filePath)
然后取消存档
if let array = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? [Any] {
objects = array
}
这是一个符合 NSCoding
的示例对象(摘自上面链接的文章):
class Person : NSObject, NSCoding {
struct Keys {
static let Name = "name"
static let Age = "age"
}
var name = ""
var age = 0
init(dictionary: [String : AnyObject]) {
name = dictionary[Keys.Name] as! String
age = dictionary[Keys.Age] as! Int
}
public func encode(with archiver: NSCoder) {
archiver.encodeObject(name, forKey: Keys.Name)
archiver.encodeObject(age, forKey: Keys.Age)
}
required init(coder unarchiver: NSCoder) {
super.init()
name = unarchiver.decodeObjectForKey(Keys.Name) as! String
age = unarchiver.decodeObjectForKey(Keys.Age) as! Int
}
}
如果数组中的对象都是 "property list objects"(字典、数组、字符串、数字(整数和浮点数)、日期、二进制数据和布尔值),那么您可以使用数组方法 write(toFile:atomically:)
将数组保存到文件,然后使用 arrayWithContentsOfFile:
或 init(contentsOfFile:)
.
重新加载生成的文件
如果数组 object graph
中的对象不是 属性 列表对象,那么该方法将不起作用。在那种情况下,@BogdanFarca 使用 NSKeyedArchiver
/NSKeyedUnarchiver
的建议将是一个很好的方法。
类似于游戏允许您保存进度的方式,我在 iOS 中有一个应用程序将用户的进度存储在一个数组中。我想将该数组存储到一个文件中,以便当用户重新打开他们的应用程序时,该文件会加载他们的当前状态。
最简单的方法是使用 NSKeyedArchiver
/NSKeyedUnarchiver
对并确保数组中的每个对象都符合 NSCoding
。您可以阅读 here。
NSKeyedArchiver.archiveRootObject(myArray, toFile: filePath)
然后取消存档
if let array = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? [Any] {
objects = array
}
这是一个符合 NSCoding
的示例对象(摘自上面链接的文章):
class Person : NSObject, NSCoding {
struct Keys {
static let Name = "name"
static let Age = "age"
}
var name = ""
var age = 0
init(dictionary: [String : AnyObject]) {
name = dictionary[Keys.Name] as! String
age = dictionary[Keys.Age] as! Int
}
public func encode(with archiver: NSCoder) {
archiver.encodeObject(name, forKey: Keys.Name)
archiver.encodeObject(age, forKey: Keys.Age)
}
required init(coder unarchiver: NSCoder) {
super.init()
name = unarchiver.decodeObjectForKey(Keys.Name) as! String
age = unarchiver.decodeObjectForKey(Keys.Age) as! Int
}
}
如果数组中的对象都是 "property list objects"(字典、数组、字符串、数字(整数和浮点数)、日期、二进制数据和布尔值),那么您可以使用数组方法 write(toFile:atomically:)
将数组保存到文件,然后使用 arrayWithContentsOfFile:
或 init(contentsOfFile:)
.
如果数组 object graph
中的对象不是 属性 列表对象,那么该方法将不起作用。在那种情况下,@BogdanFarca 使用 NSKeyedArchiver
/NSKeyedUnarchiver
的建议将是一个很好的方法。