导入UIKit
class Event:NSObject,NSCoding {
// MARK: Properties
var name: String
var created_at: String
var stands:[Stand?]
// MARK: Archiving Paths
static let DocumentsDirectory = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
static let ArchiveURL = DocumentsDirectory.URLByAppendingPathComponent("events")
// MARK: Types
struct PropertyKey {
static let nameKey = "name"
static let createdAtKey = "created_at"
static let standsAtKey = "stands"
}
// MARK: Initialization
init?(name: String, created_at: String, stands:[Stand?]) {
// Initialize stored properties.
self.name = name
self.created_at = created_at
self.stands = stands
super.init()
// Initialization should fail if there is no name or if no created_at.
if name.isEmpty || created_at.isEmpty {
return nil
}
}
// MARK: NSCoding
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(name, forKey: PropertyKey.nameKey)
aCoder.encodeObject(created_at, forKey: PropertyKey.createdAtKey)
aCoder.encodeObject(stands, forKey: PropertyKey.standsAtKey)
}
required convenience init?(coder aDecoder: NSCoder) {
let name = aDecoder.decodeObjectForKey(PropertyKey.nameKey) as! String
let created_at = aDecoder.decodeObjectForKey(PropertyKey.createdAtKey) as! String
let stands = aDecoder.decodeObjectForKey(PropertyKey.standsAtKey) as! [Stand?]
// Must call designated initializer.
self.init(name: name, created_at: created_at, stands: stands)
}
}
我收到来自“aCoder.encodeObject(stand,forKey:PropertyKey.standsAtKey)”的错误说“无法将[Stand?]类型的值转换为预期的参数类型'AnyObject?'”
我正在使用NSCoding保存具有空Stand数组的对象,然后检索它并更新此Class(Event)的Stands属性
答案 0 :(得分:0)
除非您的“Stand”类符合NSCoding标准,否则您无法对自定义类“事件”进行编码。
答案 1 :(得分:0)
在Swift 4中,您可以遵循编码解码的协议Codable
class Test: Codable {
}
有关详情,请参阅https://developer.apple.com/documentation/swift/codable