Gabe Spound
Gabe Spound

Reputation: 590

Best way to persist an Array of Custom Objects in Swift on iOS

My current solution to this problem is creating a class that implements NSObject and NSCoder and using that to encode and decode my Array of Plant Objects (Plant consists of two strings and a UIImage). It seems unnecessary that I have to create a class just so that I can use NSCoder to save an array. Is there a better way of doing this?

EDIT: To be clear, the plant class is NOT implementing NSCoder. It is simply an NSObject. I have a separate class (a singleton, if you will), that I encode and decode when the app closes and begins. That singleton, contains my Array of Plants.

EDIT: Plant Class

public class Plant: NSObject {
    private var name: String
    private var waterFrequency: Int
    private var date: Date
    private var img: UIImage
    private let dFormat = DateFormatter()

    public init(n: String, wF: Int) {
        self.name = n
        self.waterFrequency = wF
        self.date = Date();
        dFormat.dateFormat = "dd.MM.yyyy"
    }
}

Singleton

public class Singleton: NSCoder {
    private static var myPlantList: [Plant] {
        get {
            return myPlantList
        } set(pL) {
        self.myPlantList = pL
        }
    }

    private override init(pL: [Plant]){
        //init
    }

    required convenience init?(coder? aDecoder: NSCoder){
        //Decode
    }
}

Upvotes: 0

Views: 191

Answers (0)

Related Questions