2

I am trying to learn Swift and having difficulties storing an array of my custom class. Here are my classes

import Foundation

class Entry {
   var company: String
   var category: String
   var amount: Double
   var type: String

   init() {
      self.company = ""
      self.category= ""
      self.amount= ""
      self.type= ""
   }
}

I have another class that is an array of entries called a checkbook

import Foundation

class Checkbook {
   var entries = [Entry]()

   init() {
      self.entries = []
   }
}

Then in my view controller I have an array of checkbooks. I need to store that array of checkbooks so it keeps all its data next time the app opens up. What is the best way to do this?

2
  • There are many ways to do. I suggest you start with NSUserdefaults. If you have a lot of data, then you can start looking into mobile databases like core data or realm. Commented Jun 30, 2019 at 22:24
  • @YuchenZhong UserDefaults purpose is to persist the app preferences not for storing the app data. Commented Jun 30, 2019 at 23:16

1 Answer 1

2

You can use Codable protocol to encode and decode your classes to a JSON file but I recommend using structures:

struct Entry: Codable {
    let company, category, type: String
    let amount: Double
}

struct CheckBook: Codable {
    var entries: [Entry] = []
}

extension FileManager {
    static let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
}

Playground testing:

let checkBooks: [CheckBook] = [.init(entries: [.init(company: "ACME", category: "JSON", type: "Swift", amount: 5.0)])]
do {
    let destinationURL = FileManager.documentDirectory.appendingPathComponent("CheckBooks.json")
    try JSONEncoder().encode(checkBooks).write(to: destinationURL)
    print("json encoded/saved")
    let loadedCheckBooks = try JSONDecoder().decode([CheckBook].self, from: .init(contentsOf: destinationURL))
    print(loadedCheckBooks)  // CheckBook(entries: [Entry(company: "ACME", category: "JSON", type: "Swift", amount: 5.0)])\n"
} catch { 
    print(error) 
}
Sign up to request clarification or add additional context in comments.

2 Comments

I can’t get the preferences directory to work says there is no library directory and the init from decode is also not working. Also will this work for an array of checkbooks?
yes it would work. I will save to documents directory instead

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.