swiftrealmnscodingnskeyedarchiverskproduct

NSCoding error with SKProduct in Swift


I'm trying to save SKProduct in Realm but at begging I'm trying to convert SKProduct to NSData but I'm getting this error Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[SKProduct encodeWithCoder:]: unrecognized selector sent to instance 0x14f5cd200' *

My class

import Foundation
import StoreKit

class ProductDataModel: NSObject, NSCoding {

    var product = SKProduct()

    // MARK: - var and let
    private let coderKey = "ProductDataModel"

    override init() {
        super.init()
    }

    convenience init(product: SKProduct) {
        self.init()
        self.product = product
    }

    required init?(coder aDecoder: NSCoder) {
        self.product = aDecoder.decodeObjectForKey(coderKey) as! SKProduct

    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(self.product, forKey: coderKey)
    }
}

I try to archive it in another class

 let productData = ProductDataModel(product: product)
 let data = NSKeyedArchiver.archivedDataWithRootObject(productData)

I did it in different ways but the result is the same. How can I fix it?


Solution

  • We solved it that we paste SKProduct array to the singleton and use it. I know that it's a bad solution but I don't know another.