i'm newbie in swift adn i have problem with initwithcoder in swift.
I have class UserItem, i need it to save user login.
in objective c is like this
- (id)initWithCoder:(NSCoder *)decoder{
if (self = [super init]){
self.username = [decoder decodeObjectForKey:@"username"];
}
return self;
}
and in swift i'm trying like this
override init() {
super.init()
}
required init(coder decoder: NSCoder!) {
self.username = (decoder.decodeObjectForKey("username")?.stringValue)!
super.init(coder: decoder)
}
but if like above, i get error on code
super.init(coder: decoder)
error message is "extra argument 'coder' in call
i can't figure out anymore, so i'm try this code,
convenience init(decoder: NSCoder) {
self.init()
self.username = (decoder.decodeObjectForKey("username")?.stringValue)!
}
but, get error
.UserItem initWithCoder:]: unrecognized selector sent to instance 0x7fd4714ce010
what should i do? thanks before for your help.
I struggled with
NSCoding(the protocol that you use to archive and unarchive objects) in the past and I'm seeing that you are going through the same pains. Hope this lessen it a bit:The important thing is to match up the keys and the data types in
encodeWithCoder(aCoder:)(the archive function) andinit(coder:)(the unarchive function).Where is confusing for beginners is what to do with the superclass. You should only include the superclass in the two functions above if the superclass itself conforms to
NSCoding.NSObjectdoes not provide that by itself. The idea is each class knows about its own properties, some of which are private. If the superclass cannot archive/unarchive, there's no need to call them.