0

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
    }
}
Gabe Spound
  • 568
  • 5
  • 28
  • But you're not creating a class (`Plant`) just to save the array. You have a class because using a class is the proper way (actually a `struct` is probably better) to organize your two strings and image together. – rmaddy May 04 '18 at 01:15
  • @rmaddy check edit. Plant is not implementing NSCoder. I have a seperate class just for encoding and decoding the array of Plants. – Gabe Spound May 04 '18 at 01:51
  • Perhaps if you showed some relevant code and clarified what issues you are having, it would be easier to help. – rmaddy May 04 '18 at 01:55
  • @rmaddy Added code. I didn't have the Singleton Class finished, so I didn't know if it would be much help, but this should clarify what i'm trying to do. – Gabe Spound May 04 '18 at 02:18

0 Answers0