最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

[已解决]swift中enum枚举变量没法被aCoder.encodeObject

Swift crifan 2819浏览 0评论

代码:

enum ContactType{
    case Invalid
    case Special // special for Add/Remove/… items
    case Person //single person
    case Group  //a group
    case Topic  //a topic
}
class ContactItem:NSObject, NSCoding {
    var type:ContactType
 
    override init(){
        type = ContactType.Invalid
       
        super.init()
    }
   
    // MARK: NSCoding
    private let codingKey_type = "ContactItem_type"
 
    required init?(coder aDecoder: NSCoder){
        self.type = aDecoder.decodeObjectForKey(codingKey_type) as! ContactType
        super.init()
    }
   
    func encodeWithCoder(aCoder: NSCoder){
        aCoder.encodeObject(type, forKey: codingKey_type)
    }
}

出错:

Cannot convert value of type ‘ContactType’ to expected argument type ‘AnyObject?’

如图:

搜:

swift enum encodeObject Cannot convert value

swift enum encodeObject

ios – Encode/Decode enum for Swift (Xcode 6.1) – Stack Overflow

Simple NSCoding with Swift example, using enum & rawValue for the key names.

How do I encode enum using NSCoder in swift? – Stack Overflow

Encode/decode enums using NSCoder methods | petosoft

NSCoder and Swift structs and enums | Apple Developer Forums

Introducing Protocol-Oriented Programming in Swift 2 – Ray Wenderlich

Archiving and unarchiving structs, enums and ot… | Apple Developer Forums

Serializing generic structs | Apple Developer Forums

好像没法去coding这样:

enum ContactType{
    case Invalid
    case Special // special for Add/Remove/… items
    case Person //single person
    case Group  //a group
    case Topic  //a topic
}

的enum 

感觉是:

必须让enum去继承某种类型,比如String,Int之类的。

此处加上String,然后就可以encode了:

enum ContactType:String{
    case Invalid
    case Special // special for Add/Remove/… items
    case Person //single person
    case Group  //a group
    case Topic  //a topic
}
class ContactItem:NSObject, NSCoding {
    var type:ContactType
    func encodeWithCoder(aCoder: NSCoder){
        aCoder.encodeObject(type.rawValue, forKey: codingKey_type)
    }
}

[后记 2016-01-14]

后来:

[已解决]swift中枚举值decodeObjectForKey失败

中发现,之前的:

self.personType = aDecoder.decodeObjectForKey(codingKey_personType) as! PersonType

是错误的。

应该改为:

        let rawPersonTypeStr = aDecoder.decodeObjectForKey(codingKey_personType) as! String //"Colleague"
        self.personType = PersonType(rawValue: rawPersonTypeStr)! //JianDao.PersonType.Colleague

即:

self.personType = PersonType(rawValue: aDecoder.decodeObjectForKey(codingKey_personType) as! String)!

才可以正常解码。

转载请注明:在路上 » [已解决]swift中enum枚举变量没法被aCoder.encodeObject

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
91 queries in 0.194 seconds, using 22.15MB memory