如何快速保存类变量?

时间:2019-03-12 10:01:09

标签: swift variables core-data save

我上课:

class Dream {
    var name: String?
    var timeStamp = Date()
}

我想保存所有变量

我正在尝试保存在 UserDefaults 中-但这是错误的方式

我认为它应该保存在 CoreData 中,但是我不知道该怎么做,有人可以帮助我吗?

var item: [Dream] = []

func addItem(nameItem: Dream) {
    item.append(nameItem)
}

func removeItem(at index: Int){
    item.remove(at: index)
}

我在IBAction中使用func addItem

@IBAction func saveButton(_ sender: Any) {
        let image = categoryImage.image
        let data = image!.jpegData(compressionQuality: 0.5)!
        let date = Date()
        let name = date.description
        do {
            let documentDirectory = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor:nil, create:false)
            let fileURL = documentDirectory.appendingPathComponent(name)

            try data.write(to: fileURL)

            print(fileURL)

        } catch {
            print(error.localizedDescription)
        }
        let dream = Dream()
        dream.timeStamp = date
        dream.name = nameTextField.text

        addItem(nameItem: dream)
        navigationController?.popViewController(animated: true)
    }

1 个答案:

答案 0 :(得分:0)

您不应该将图像数据真正保存在CoreData或UserDefaults中(后者只是一个.plist文件),因为图像通常会很大。

最好保存图像的String(?)值,例如作为可选的imageUrlString,并从中获取可选的计算的var imageUrl: URL?。然后可以在应用加载时或需要时(例如,使用PINRemoteImage [github page])来检索图像。

下面是一个UserDefaults示例,其中只有一个,但是您可以存储Dream个组件的字典(或使用类似Realm [docs]或{{1 }} [docs]来存储更完整的CoreData实例)

Dream

然后,您可以使用import Foundation import UIKit import PINRemoteImage class Dream { var imageUrlString: String? var name: String? var timeStampString: String = "" init(fromUserDefaults: Bool) { if fromUserDefaults { self.imageUrlString = StorageService.instance.imageUrlString self.name = StorageService.instance.nameString self.timeStampString = StorageService.instance.timeStampString } } } extension Dream { var imageUrl: URL? { guard let imageUrlString = imageUrlString else { return nil } return URL(string: imageUrlString) } var timeStamp: Date? { //Insert logic here to return a date in the desired format, from the timeStampString - e.g. let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") //For example formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss" //For example guard let dateFromString = formatter.date(from: timeStampString) else { return nil } return dateFromString } } //Create a singleton to handle access to userDefaults safely class StorageService { //MARK: Singleton static let instance = StorageService() //MARK: Private initialiser private init() {} private enum UserDefaultsKeys: String { case imageUrlString case nameString case timeStampString } var imageUrlString: String? { get { return UserDefaults.standard.string(forKey: UserDefaultsKeys.imageUrlString.rawValue) ?? nil } set { UserDefaults.standard.set(newValue, forKey: UserDefaultsKeys.imageUrlString.rawValue) } } var nameString: String? { get { return UserDefaults.standard.string(forKey: UserDefaultsKeys.nameString.rawValue) ?? nil } set { UserDefaults.standard.set(newValue, forKey: UserDefaultsKeys.nameString.rawValue) } } var timeStampString: String { get { return UserDefaults.standard.string(forKey: UserDefaultsKeys.timeStampString.rawValue) ?? "" } set { UserDefaults.standard.set(newValue, forKey: UserDefaultsKeys.timeStampString.rawValue) } } } (或其他方式)从梦想实例中的任意位置加载图像,例如:

pin_setImage