推荐使用值类型,并把我们定义的标准的值,简单的结构化数据,应用状态等定义为结构体或枚举。Pencil使得存储这些值更加容易。
CocoaPods
pod 'pencil'
Swift Package Manager
兼容。
手动
将包含在Sources
目录中的所有*.swift
文件复制到您的项目中。
Int
值写入设备上的文件并在那里读取它。// (create stored url)
guard let storedURL = Directory.Documents?.append(path: "int.data") else {
return
}
let num: Int = 2016
// write
num.write(to: storedURL)
// ...
// read
let stored: Int? = Int.value(from: storedURL)
let text: String = "Pencil store value easily."
text.write(to: storedURL)
// ...
let stored: String? = String.value(from: storedURL)
let nums: [Int] = [2016, 11, 28]
nums.write(to: storedURL)
// ...
let stored: [Int]? = [Int].value(from: storedURL)
let dictionary: [String: Int] = ["year": 2016, "month": 11, "day": 28]
dictionary.write(to: storedURL)
// ...
let stored: [String: Int]? = [String: Int].value(from: url)
其他标准可写和可读值包括Bool
、Float
、Double
、Date
、Int8
、Int16
、Int32
、Int64
、UInt
、UInt8
、UInt16
、UInt32
和UInt64
。
原始值类型应符合ReadWriteElement
,并为枚举添加ReadWriteElement
。
enum Sample: Int, ReadWriteElement {
case one = 1
case two = 2
}
使用与标准值相同的方式进行读写。
let sample: Sample = .two
sample.write(to: storedURL)
// ...
let stored: Sample? = Sample.value(from: url)
Sample
)。CustomReadWriteElement
。static func read
并返回 Sample
或 nil
。struct Sample: CustomReadWriteElement {
let dictionary: [String: Int]
let array: [Int]?
let identifier: String
static func read(components: Components) -> Sample? {
do {
return try Sample(
dictionary: components.component(for: "dictionary"),
array: components.component(for: "array"),
identifier: components.component(for: "identifier")
)
} catch {
return nil
}
}
}
使用与标准值相同的方式进行读写。
let sample: Sample = Sample(dictionary: ["one": 2, "two": 5], array: [2, 3], identifier: "abc123")
sample.write(to: storedURL)
// ...
let stored: Sample? = Sample.value(from: url)
现在您可以写入和读取包含自定义结构体的复杂值。
let sample: Sample = Sample(dictionary: ["one": 2, "two": 5], array: [2, 3], identifier: "abc123")
let samples: [Samples] = [sample, sample, sample]
samples.write(to: storedURL)
// ...
let stored: [Sample]? = [Sample].value(from: url)
定义具有默认参数的自定义结构体。如果所有属性都具有默认值或可选,则不需要使用 try
。
struct Sample: CustomReadWriteElement {
let dictionary: [String: Int]
let array: [Int]?
let identifier: String
static func read(components: Components) -> Sample? {
return Sample(
dictionary: components.component(for: "dictionary", defaultValue: ["default": 100]),
array: components.component(for: "array"),
identifier: components.component(for: "identifier", defaultValue: "default")
)
}
}
Pencil 支持使用 Directory
类创建文件路径。
// Create path ~/Documents/pencil.data
let url: URL? = Directory.Documents?.append(path: "pencil.data")
其他目录有 Applications
、Demos
、Documentation
、Documents
、AutosavedInformation
、Caches
和 Downloads
。
Pencil 是在 MIT 许可下发布的。有关详细信息,请参阅 LICENSE。