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") 
    } 
} 

가 호출 : 인해 캐치되지 않는 예외 'NSInvalidArgumentException', 이유에 *** 응용 프로그램을 종료 :Swift 3에서 NSCoder를 사용하여 [Character : Int] 속성을 어떻게 인코딩합니까?

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") 
     } 
    } 
} 

엑스 코드에서 오류가 발생합니다 '- [_ SwiftValue encodeWithCoder는 :] : 인식 할 수없는 선택기 인스턴스에 전송

+0

어떻게 부르십니까? – Rikh

+0

죄송합니다. 답변을 주셔서 감사합니다. – Max

답변

2
cx에서 Character -typed 키 _SwiftValue 개체로 박스형되기 때문이다

이유

어느 인식 할 수없는 선택기 예외로 연결되는 encodeWithCoder:이 전송됩니다. 당신이 [String : Int]cx의 유형을 변경할 수있는 경우

이 모든 것이 (웃기려는 의도 없음) 상자 밖으로 작동합니다

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.

솔루션 :

SwiftValue.h 상단의 의견을 참조하십시오 .

그렇지 않으면 cxFoo.encode(with:)을 디코딩 초기화 프로그램에서 인코딩 할 수있는 코드로 변환해야합니다 (예 : [String : Int]). 반대의 경우도 마찬가지입니다.

일부 코드의 경우 How do I encode Character using NSCoder in swift?How do I encode enum using NSCoder in swift?을 참조하십시오.

+0

감사합니다. – Max

관련 문제