保存不断追加的自定义对象数组

时间:2018-11-22 15:13:23

标签: arrays swift save

我一般都不熟悉Swift和编码。我目前正在尝试磨练自己的技能,但将其组装成一个简单的提醒应用程序。在组装故事板之前,我正在尝试使后端工作,但是我有必要的故事板元素来测试我的系统是否可以工作。

基本上,我正在尝试保存一个包含自定义对象的数组,但是此数组会附加到用户完成的每个提醒添加中。这样一来,每次打开应用程序时,数组都会包含上次的提醒。

这是我到目前为止创建和添加列表的代码;

func createReminder() {
    let reminderAdd = Reminder(chosenReminderDescription: textRetrieve.text!, chosenReminderLength: 1)
    reminderList.append(reminderAdd)

    dump(reminderList)
}

这是目标代码;

class Reminder {

    var reminderDescription = "Require initalisation."
    var reminderLength = 1 // in days

    init (chosenReminderDescription: String, chosenReminderLength: Int) {
        reminderDescription = chosenReminderDescription
        reminderLength = chosenReminderLength
    }

}

我将如何保存阵列?

编辑: 这是我到目前为止添加的内容。

    override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let reminderAdd = Reminder(chosenReminderDescription: "Placeholder test", chosenReminderLength: 1)
    reminderList.append(reminderAdd)

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext

    let entity = NSEntityDescription.entity(forEntityName: "Tasks", in: context)
    let newTask = NSManagedObject(entity: entity!, insertInto: context)

    newTask.setValue(reminderList, forKey: "taskName")

    do {
        try context.save()
    } catch {
        print("Failed saving")
    }

    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Tasks")
    //request.predicate = NSPredicate(format: "age = %@", "12")
    request.returnsObjectsAsFaults = false
    do {
        let result = try context.fetch(request)
        for data in result as! [NSManagedObject] {
            print(data.value(forKey: "taskName"))
        }

    } catch {

        print("Failed")
    }

我崩溃了,到目前为止我似乎还不能调试它。我相信这行会导致崩溃,因为当我将其删除时,应用程序可以正常启动。

let reminderAdd = Reminder(chosenReminderDescription: "Placeholder test", chosenReminderLength: 1)
    reminderList.append(reminderAdd)

有什么想法吗?

编辑2: datamodel

那是数据模型,我不确定要使对象变成可编码的含义。再次感谢。

编辑3:

ViewDidLoad

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib

    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext

    let entity = NSEntityDescription.entity(forEntityName: "Tasks", in: context)
    let newTask = Tasks(entity: entity!, insertInto: context)

    newTask.setValue(reminderList, forKey: "taskName")

    do {
        try context.save()
    } catch {
        print("Failed saving")
    }

    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Tasks")

    //request.predicate = NSPredicate(format: "age = %@", "12")
    request.returnsObjectsAsFaults = false
    do {
        let result = try context.fetch(request)
        for data in result as! [Tasks] {
            print(data.value(forKey: "taskName"))

        }

    } catch {

        print("Failed")
    }

    dump(reminderList)
}

1 个答案:

答案 0 :(得分:-1)

您可以使用CoreData创建一个实例,并将其像内部数据库一样存储。 这些是一些很好的入门教程:

https://medium.com/xcblog/core-data-with-swift-4-for-beginners-1fc067cca707

https://www.raywenderlich.com/7569-getting-started-with-core-data-tutorial

编辑2

如您在此图中看到的, https://ibb.co/f1axcA 我在coreData中的列表是[Notifica]类型,因此是一个对象Notifica数组,要实现可编码,您应该执行以下操作

public class Notifica: NSObject, NSCoding {

public required init?(coder aDecoder: NSCoder) {
    self.id = aDecoder.decodeObject(forKey: "id") as? Double
    self.type = aDecoder.decodeObject(forKey: "type") as? String
    self.idEvent = aDecoder.decodeObject(forKey: "idEvent") as? Int
    self.contactPerson = aDecoder.decodeObject(forKey: "contactPerson") as? People
    self.title = aDecoder.decodeObject(forKey: "title") as? String
    self.date = aDecoder.decodeObject(forKey: "date") as? String
}

public func encode(with aCoder: NSCoder) {
    aCoder.encode(id, forKey: "id")
    aCoder.encode(type, forKey: "type")
    aCoder.encode(idEvent, forKey: "idEvent")
    aCoder.encode(contactPerson, forKey: "contactPerson")
    aCoder.encode(title, forKey: "title")
    aCoder.encode(date, forKey: "date")
}

ecc..

另一件事是不调用NSManagedObject并传递实体,但是您应该像在dataModel中调用的那样命名Tasks,如果在xcode上键入Tasks,它将为您查找创建的NSManagedObject,然后可以为taskName设置值

编辑3

<Simple_Reminders.Reminder: 0x60400046da40>”表示存在一个Reminder对象!这样就保存了!提醒有两个变量: -reminderDescription和 -reminderLength,因此更改您的代码

do {
    let result = try context.fetch(request)
    for data in result as! [Tasks] {
        print(data.value(forKey: "taskName"))

    }

} catch {

    print("Failed")
}

与此

do {
    let result = try context.fetch(request)
    for data in result as! [Tasks] {
        print(data.value(forKey: "taskName"))
        if let reminders = data.value(forKey: "taskName") as? [Reminder] {
            for reminder in reminders {
                // Now you have your single object Reminder and you can print his variables
                print("Your reminder description is \(reminder. reminderDescription), and his length is \(reminder. reminderLength))"
            }
        }
    }

} catch {

    print("Failed")
}