如何使用RLMArray保存数组 [英] How to use RLMArray to save an Array

查看:853
本文介绍了如何使用RLMArray保存数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:我对Realm和Swift相当新,所以请原谅任何我不理解的明显事情。

Note: I am fairly new to Realm and Swift, so excuse any obvious things I don't understand.

我有一个工作的UITableView我计划填充有任务。我希望用户能够根据需要添加和删除任务,因此我无法对任务进行硬编码,并且我希望在应用程序启动之间保存任务。最明显的方法是创建一个在Realm中保存的数组。问题是,我不明白如何在Realm中保存数组。我已经阅读了Realm网站上的文档,但由于我自己仍然是Swift的新手(并且它在ObjC中),因此发现它相当混乱。你会如何创建一个数组并保存它?我最初尝试过这个,当它不起作用我做了一些研究,发现RLMArray实际上不是一个数组:

I have a working UITableView which I plan to populate with tasks. I want the user to be able to add and delete tasks as needed, so I can't hardcode the tasks, and I want the tasks to be saved between app launches. The most obvious way to do this would be to create an array that gets saved in Realm. The problem is, I don't understand how to save an array in Realm. I have read the documentation on the Realm site but have found it rather confusing due to myself still being fairly new to Swift (And that it's in ObjC). How would you create an array and save it? I originally tried this, and when it didn't work I did some research and found that RLMArray isn't actually an array:

let ToDoTasksArray: RLMArray = ["Task Goes Here", "Task Goes Here2"]

任何帮助在这?谢谢!

编辑:

我也尝试将数组保存为RLMObject作为对象,如下所示:

I have also tried saving an array into an RLMObject as an object as so:

realm.addObject(ToDoTasksArray)

但这也行不通,这并不让我感到惊讶。数组不是对象。

But that also doesn't work, which doesn't surprise me. An array is not an object.

推荐答案

首先需要设置模型,以便将待办事项保存到领域。

you first need to setup your models so that your todo's can be saved to the realm.

你需要做的就是在你的一个文件中有这个(最好是一个todo.swift文件)

All you need to do is have this in one of your files (Preferably a todo.swift file)

class Todo: RLMObject {
  dynamic var name = ""
}

然后你可以通过这样做来创建前两个待办事项:

Then you can create your first two todos by doing this:

var firstTodo = Todo()
firstTodo.name = "My first thing todo!"

var secondTodo = Todo()
secondTodo.name = "My second thing todo!"

然后你可以把它保存到领域

Then you can save it to the realm

let realm = RLMRealm.defaultRealm()
realm.beginWriteTransaction()
realm.addObject(firstTodo)
realm.addObject(secondTodo)
realm.commitWriteTransaction()

现在你可以获取所有返回它们的todos

Now you can grab all of your todos which returns an array of them

let arrayOfTodos = Todo.allObjects()

如果我要创建一种保存新待办事项的方法,我会做这样的事情

If I were to create a method to save new todos I'd do something like this

func createNewTodo(todo: String){
    let todo = Todo()
    todo.name = todo
    let realm = RLMRealm.defaultRealm()
    realm.beginWriteTransaction()
    realm.addObject(todo)
    realm.commitWriteTransaction()
}

这篇关于如何使用RLMArray保存数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆