2017-04-08 1 views
3
import UIKit 

class Foo: NSObject, NSCoding { 
    var cx: [Character : Int] 

    init(cx: [Character : Int]) { 
     self.cx = cx 
    } 

    // MARK: - <NSCoding> 

    required convenience init(coder aDecoder: NSCoder) { 
     let cx = aDecoder.decodeObject(forKey: "cxKey") as! [Character : Int] 
     self.init(cx: cx) 
    } 

    func encode(with aCoder: NSCoder) { 
     aCoder.encode(cx, forKey: "cxKey") 
    } 
} 

calling:Wie kann ich die Eigenschaft [Character: Int] mit NSCoder in Swift 3 kodieren?

class ViewController: UIViewController { 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Do any additional setup after loading the view, typically from a nib. 

     var foo = Foo(cx: ["C": 5, "X": 6]) 

     let encodedData = NSKeyedArchiver.archivedData(withRootObject: foo) 
     print("encodedData: \(encodedData))") 

     if let foo1 = NSKeyedUnarchiver.unarchiveObject(with: encodedData) as? Foo { 
      print("cx = ", foo1.cx) 
     } else{ 
      print("There is an issue") 
     } 
    } 
} 

Xcode wirft einen Fehler: *** Beenden app aufgrund nicht abgefangene Ausnahme 'NSInvalidArgumentException', Grund: ‚- [_ SwiftValue encodeWithCoder:]: Unbekannter Selektor gesendet Instanz

+0

Wie nennst du es? – Rikh

+0

Entschuldigung, hinzugefügt – Max

Antwort

2

Grund

das heißt, weil die Character -typed Schlüssel in cx als _SwiftValue Objekte geschachtelt werden, die wird encodeWithCoder: gesendet, was zu der nicht erkannten Selektorausnahme führt.

Siehe Kommentar an der Spitze SwiftValue.h:

This implements the Objective-C class that is used to carry Swift values that have been bridged to Objective-C objects without special handling. The class is opaque to user code, but is NSObject - and NSCopying - conforming and is understood by the Swift runtime for dynamic casting back to the contained type.

Lösung

Wenn Sie die Art von cx zu [String : Int] ändern können, alles aus der Box funktioniert (kein Wortspiel beabsichtigt) .

Andernfalls müssen Sie cx in Foo.encode(with:), um etwas zu konvertieren, die (wie [String : Int], zum Beispiel) codiert werden können und umgekehrt bei der Decodierung initializer.

Für einen Code siehe How do I encode Character using NSCoder in swift? und How do I encode enum using NSCoder in swift?.

+0

danke für Ihre Antwort – Max

Verwandte Themen