How to encode initwithcoder in Swift?

I am new to swift and see that I have a problem with initwithcoder in swift.

I have a UserItem class, I need to save it the user login.

in object c is like this

 - (id)initWithCoder:(NSCoder *)decoder{
    if (self = [super init]){
        self.username = [decoder decodeObjectForKey:@"username"];
    }
    return self;
}

and in swift I try so hard

override init() {
   super.init()
}    

required init(coder decoder: NSCoder!) {

   self.username = (decoder.decodeObjectForKey("username")?.stringValue)!

   super.init(coder: decoder)
}

but if, for example, above, I get an error in the code

super.init(coder: decoder)

the error message is an “optional encoder” argument when called

I can no longer understand, so I'm trying to use this code,

convenience init(decoder: NSCoder) {
   self.init()

   self.username = (decoder.decodeObjectForKey("username")?.stringValue)!
}

but get an error

.UserItem initWithCoder:]: unrecognized selector sent to instance 0x7fd4714ce010

what should I do? Thanks first for your help.

+4
source share
1 answer

In the past, I struggled with NSCoding(the protocol that you use to archive and unlock objects), and I see that you are experiencing the same pains. Hope this reduces this a bit:

class UserItem: NSObject, NSCoding {
    var username: String
    var anInt: Int

    init(username: String, anInt: Int) {
        self.username = username
        self.anInt = anInt
    }

    required init?(coder aDecoder: NSCoder) {
        // super.init(coder:) is optional, see notes below
        self.username = aDecoder.decodeObjectForKey("username") as! String
        self.anInt = aDecoder.decodeIntegerForKey("anInt")
    }

    func encodeWithCoder(aCoder: NSCoder) {
        // super.encodeWithCoder(aCoder) is optional, see notes below
        aCoder.encodeObject(self.username, forKey: "username")
        aCoder.encodeInteger(self.anInt, forKey: "anInt")
    }

    // Provide some debug info
    override var description: String {
        get {
            return ("\(self.username), \(self.anInt)")
        }
    }
}

// Original object
let a = UserItem(username: "michael", anInt: 42)

// Serialized data
let data = NSKeyedArchiver.archivedDataWithRootObject(a)

// Unarchived from data
let b = NSKeyedUnarchiver.unarchiveObjectWithData(data)!

print(a)
print(b)

encodeWithCoder(aCoder:) ( ) init(coder:) ( unarchive).

- . , NSCoding. NSObject . , , . /, .

+11

Source: https://habr.com/ru/post/1617927/


All Articles