0
votes

import UIKit

class Event: NSObject, NSCoding {

// MARK: Properties
var name: String
var created_at: String
var stands:[Stand?]

// MARK: Archiving Paths

static let DocumentsDirectory = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
static let ArchiveURL = DocumentsDirectory.URLByAppendingPathComponent("events")


// MARK: Types

struct PropertyKey {
    static let nameKey = "name"
    static let createdAtKey = "created_at"
    static let standsAtKey = "stands"

}

// MARK: Initialization
init?(name: String, created_at: String, stands:[Stand?]) {
    // Initialize stored properties.
    self.name = name
    self.created_at = created_at
    self.stands = stands

    super.init()

    // Initialization should fail if there is no name or if no created_at.
    if name.isEmpty || created_at.isEmpty {
        return nil
    }
}

// MARK: NSCoding
func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeObject(name, forKey: PropertyKey.nameKey)
    aCoder.encodeObject(created_at, forKey: PropertyKey.createdAtKey)
    aCoder.encodeObject(stands, forKey: PropertyKey.standsAtKey)

}

required convenience init?(coder aDecoder: NSCoder) {
    let name = aDecoder.decodeObjectForKey(PropertyKey.nameKey) as! String

    let created_at = aDecoder.decodeObjectForKey(PropertyKey.createdAtKey) as! String

    let stands = aDecoder.decodeObjectForKey(PropertyKey.standsAtKey) as! [Stand?]

    // Must call designated initializer.
    self.init(name: name, created_at: created_at, stands: stands)
}

}

I have got error from "aCoder.encodeObject(stands, forKey: PropertyKey.standsAtKey)" saying "Cannot convert value of type[Stand?] to expected argument type 'AnyObject?'"

I am using NSCoding to save the object with array of empty Stand, then later retrieve it and update the Stands property of this Class (Event)

2
Can you add the code for Stand? - tktsubota

2 Answers

0
votes

You cannot encode your custom class "Event" unless your class "Stand" is also NSCoding compliant.

0
votes

In Swift 4 you can conform to the protocol Codable which does the encoding en decoding

class Test: Codable {

}

For more information, read https://developer.apple.com/documentation/swift/codable