[英]Archiving and Unarchiving in Swift 3.0
I have some problems regarding archiving and unarchiving data in swift 3.0 . 在swift 3.0中,有关存档和取消存档数据存在一些问题。
I read some posts about the same but still don't have complete clarity about some cases. 我读了一些差不多的文章,但是对于某些情况仍然不完全清楚。
enum
(I used rawValue
to archive it.) enum
(我使用rawValue
进行存档。)
struct
(I read about the extension
method to archive it in http://swiftandpainless.com/nscoding-and-swift-structs/ ). struct
(我在http://swiftandpainless.com/nscoding-and-swift-structs/中了解了将其存档的extension
方法)。 Is there any other way to do it? 还有其他方法吗?
Array
Since array
is also a struct
, so it must also follow the archiving convention same as of a struct
. 由于
array
也是struct
,因此它也必须遵循与struct
相同的归档约定。 But I am able to archive an array
of basic data types eg. 但是我能够存档
array
基本数据类型,例如。 String, Int
etc. directly. 直接为
String, Int
等。 ie 即
let arr = ["1", "2"]
, is archived directly without any extension
. let arr = ["1", "2"]
直接存档,没有任何extension
。
Also, how does it work in an array of custom objects
? 另外,它如何在
array of custom objects
工作?
Set
Dictionary
I had the same issue and found this solution for my struct: 我遇到了同样的问题,并为我的结构找到了以下解决方案:
struct Series {
var name: String?
var season: String?
var episode: String?
init(name: String?, season: String?, episode: String?) {
self.name = name
self.season = season
self.episode = episode
}
static func archive(w: Series) -> Data {
var fw = w
return Data(bytes: &fw, count: MemoryLayout<Series>.stride)
}
static func unarchive(d: Data) -> Series {
guard d.count == MemoryLayout<Series>.stride else {
fatalError("Error!")
}
var w: Series?
d.withUnsafeBytes({(bytes: UnsafePointer<Series>) -> Void in
w = UnsafePointer<Series>(bytes).pointee
})
return w!
}
} }
I can call the archiver like this: 我可以这样称呼存档器:
var series = [Series]()
let arcData = Series.archive(w: series[0])
and the unarchiver like this: 和这样的取消归档的人:
var seriesItems = [Data]()
let unarcData = [Series.unarchive(d: seriesItems[0])]
But when I enter a name with a space the app crashes. 但是,当我输入带有空格的名称时,应用程序崩溃。 I don't no why, because in case of season and episode there are also spaces like in "Season 1".
我不知道为什么,因为在季节和剧集的情况下,“ Season 1”中也有类似的空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.