Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 保存不断追加的自定义对象数组_Arrays_Swift_Save - Fatal编程技术网

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

Arrays 保存不断追加的自定义对象数组,arrays,swift,save,Arrays,Swift,Save,一般来说,我对Swift和编码比较陌生。目前我正在努力磨练自己的技能,但我正在开发一个简单的提醒应用程序。在我组装故事板之前,我试图让后端工作,但我有必要的故事板元素来测试我的系统是否能工作 基本上,我试图保存一个包含自定义对象的数组,但是这个数组会附加到用户所做的每个提醒添加中。这样,每次应用程序打开时,阵列都会包含上次的提醒 以下是我到目前为止创建和附加列表的代码 func createReminder() { let reminderAdd = Reminder(chosenRem

一般来说,我对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")
    }
有什么想法吗

编辑2:

这就是数据模型,我不完全确定将对象转换为可编码对象是什么意思。再次感谢

编辑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)
}
override func viewDidLoad(){
super.viewDidLoad()
//加载视图后,通常从nib执行任何其他设置
让appDelegate=UIApplication.shared.delegate为!appDelegate
让上下文=appDelegate.persistentContainer.viewContext
让entity=NSEntityDescription.entity(名为“Tasks”,在:context中)
让newTask=Tasks(实体:entity!,insertInto:context)
newTask.setValue(提醒列表,forKey:“任务名”)
做{
尝试context.save()
}抓住{
打印(“保存失败”)
}
let request=NSFetchRequest(entityName:“任务”)
//request.predicate=NSPredicate(格式:“年龄=%@”,“12”)
request.returnsObjectsAsFaults=false
做{
let result=try context.fetch(请求)
将结果中的数据作为![任务]{
打印(data.value(forKey:“taskName”))
}
}抓住{
打印(“失败”)
}
转储(提醒列表)
}

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

编辑2

如图所示, 我在coreData中的列表是[Notifica]类型,对象Notifica数组也是,要实现codable,您应该这样做

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中调用的方式命名任务,如果您在xcode上键入Tasks,它将为您创建NSManagedObject,然后您可以设置taskName的值

编辑3

”表示存在提醒对象!所以你救了它!提醒有两个变量: -提醒说明和 -提醒长度,因此更改您的代码

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")
}

您可以将其保存到
.json
文件、
sqlite
数据库、
NSUserDefaults
、将其发送到某个位置的云或许多其他持久性替代方案。你试过什么?@Ian不使用UserDefaults来存储应用程序数据。@rmaddy我是说,我说可以,不应该,对吧?:)@IanMacDonald我把用户默认设置搞砸了,但没能让它工作。今晚我会有一场比赛,看看我能想出什么。@IanMacDonald我已经把核心数据弄得乱七八糟,但我只是遇到了更多的问题。我相信数据正在保存和获取,但现在我已尝试向数组添加值,以便它可以实际保存不只是空数组的内容,它会崩溃,请参阅我的编辑。谢谢,Sav。我已经把核心数据弄得乱七八糟了,但我只是遇到了更多的问题。我相信数据正在保存和获取,但现在我已尝试向数组添加值,以便它可以实际保存不只是空数组的内容,它会崩溃,请参阅我的编辑。谢谢,Sav.let newTask=NSManagedObject(entity:entity!,insertInto:context)首先你应该使用你的对象“提醒”而不是NSManagedObject,然后你应该将你的对象“提醒”修改成一个可编码的文件,我能看看你是如何创建数据库的吗?xcdatamodeld?@francecodestino我又编辑了一次,显示了数据模型。如何将提醒对象更改为可编码对象?@FrancescoDestino我相信这已经奏效了,但现在我只是从未包装的可选项中得到了一个崩溃,因为xcode不接受?而只接受!。我相信这是因为数组中没有设置值。在过去的30分钟里,我一直在尝试修复:致命错误:在展开可选值时意外发现nil,我无法更正此错误。你有什么建议?非常感谢。
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")
}