Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Coding
//
// main.swift
// TestRecursiveNSArchive
//
// Created by Helge Hess on 09.12.17.
// Copyright © 2017 ZeeZide GmbH. All rights reserved.
//
import Foundation
class Customer : NSObject, NSCoding {
let name: String
var card: CreditCard?
init(name: String) {
self.name = name
}
deinit { print("\(name) is being deinitialized") }
public func encode(with aCoder: NSCoder) {
aCoder.encode(name, forKey: "name")
aCoder.encode(card, forKey: "card")
}
required public init?(coder aDecoder: NSCoder) {
guard let name = aDecoder.decodeObject(forKey: "name") as? String
else { return nil }
self.name = name
card = aDecoder.decodeObject(forKey: "card") as? CreditCard
}
override var description: String {
return "<Author: name=\(name) card=\(card as Optional)>"
}
}
class CreditCard : NSObject, NSCoding {
// replace UInt64 w/ Int64 since there is no matching coder func
let number: Int64
unowned let customer: Customer
init(number: Int64, customer: Customer) {
self.number = number
self.customer = customer
}
deinit { print("Card #\(number) is being deinitialized") }
public func encode(with aCoder: NSCoder) {
aCoder.encode(number, forKey: "number")
aCoder.encode(customer, forKey: "customer")
}
required public init?(coder aDecoder: NSCoder) {
guard let customer = aDecoder.decodeObject(forKey: "customer") as? Customer
else { return nil }
self.number = aDecoder.decodeInt64(forKey: "number")
self.customer = customer
}
override var description: String {
return "<CC: number=\(number)>"
}
}
let john = Customer(name: "John Appleseed")
john.card = CreditCard(number: 1234_5678_9012_3456, customer: john)
print("john: \(john)")
let data = NSKeyedArchiver.archivedData(withRootObject: john)
let newJohn = NSKeyedUnarchiver.unarchiveObject(with: data)!
print("newJohn: \(newJohn)")
@helje5
Copy link
Author

helje5 commented Dec 9, 2017

Gives:

john: <Author: name=John Appleseed card=Optional(<CC: number=1234567890123456>)>
newJohn: <Author: name=John Appleseed card=Optional(<CC: number=1234567890123456>)>

@helje5
Copy link
Author

helje5 commented Dec 9, 2017

BTW: there is also a bug in NSCoder or NSUnarchiver. It sends replacementObjectForCoder: w/o checking whether the instance has it or not (only reason I inherit from NSObject above). That should either be part of NSCoding then, or be optional.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment