【发布时间】:2016-05-10 07:43:07
【问题描述】:
所以我有两个模型;联系和组,并正在通过 NSCoder 归档/取消归档他们的数据。考虑一下:
class Contact
{
var id: Int = default_value
var name: String = ""
var number: String = ""
init?(Id:Int, Name:String, Number:String)
{
self.id = Id
self.name = Name
self.number = Number
super.init()
if Id == default_value{
return nil
}
}
// MARK: NSCoding
func encodeWithCoder(aCoder: NSCoder)
{
aCoder.encodeInteger(id, forKey: "id")
aCoder.encodeInteger(name, forKey: "name")
aCoder.encodeBool(number, forKey: "number")
}
required convenience init?(coder aDecoder: NSCoder)
{
let Id = aDecoder.decodeIntegerForKey("id")
let Name = aDecoder.decodeIntegerForKey("name")
let Number = aDecoder.decodeBoolForKey("number")
self.init(Id:Id, Name:Name, Number:Number)
}
}
这真的很好,但是当我尝试在我的组模型中使用联系人时,它只是搞砸了 = 给出这个错误“无法将联系人类型的值分配给联系人?”;
class group
{
var id: Int = default_value
var contact = Contact?.self //wont let me declare a Contact
init?(Id:Int, cont:Contact)
{
self.id = Id
self.contact = cont //Cannot assign Value of type Contact to Contact?
super.init()
if Id == default_value{
return nil
}
}
// MARK: NSCoding
func encodeWithCoder(aCoder: NSCoder)
{
aCoder.encodeInteger(id, forKey: "id")
aCoder.encodeInteger(contact, forKey: "contact")
}
required convenience init?(coder aDecoder: NSCoder)
{
let Id = aDecoder.decodeIntegerForKey("id")
let Cont = aDecoder.decodeIntegerForKey("contact")
self.init(Id:Id, cont:Cont)
}
}
请告诉我我应该怎么做,因为我没有所有参数来初始化整个联系人。提前谢谢你:)
【问题讨论】:
-
您的变量声明可能只是
var contact: Contact在您的Group模型中。另外,您已将您的班级称为contact,但在group中使用了Contact,但我认为这只是一个错字? -
只是搞砸了?到底发生了什么?
-
@stefandouganhyde 是的错字.. 已修复
-
@CW0007007 messes bad = 无法分配类型的值
-
这就是命名约定总是以小写开头的变量和以大写字母开头的类。这可以极大地避免混淆。
标签: ios swift2 xcode7 optional nscoder