首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSCoding encodeObject错误

NSCoding encodeObject错误
EN

Stack Overflow用户
提问于 2016-02-12 04:18:02
回答 2查看 119关注 0票数 0

导入UIKit

类事件: NSObject,NSCoding {

代码语言:javascript
复制
// 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(stands,forKey: PropertyKey.standsAtKey)“中得到错误,说”无法将typeStand?的值转换为预期的参数类型'AnyObject?'“

我使用NSCoding来保存带有空看台数组的对象,然后检索它并更新这个类(事件)的看台属性。

EN

回答 2

Stack Overflow用户

发布于 2016-03-07 21:08:08

除非你的类"Stand“也兼容NSCoding,否则你不能对你的自定义类"Event”进行编码。

票数 0
EN

Stack Overflow用户

发布于 2017-06-09 00:43:40

在Swift 4中,您可以遵循Codable协议进行编码和解码

代码语言:javascript
复制
class Test: Codable {

}

有关更多信息,请阅读https://developer.apple.com/documentation/swift/codable

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35349217

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档