Note: I am fairly new to Realm and Swift, so excuse any obvious things I don\'t understand.
I have a working UITableView which I plan to populate with tasks. I want
Realm saves objects derived from RLMObject, so you need to define class for your task like:
@interface Task : RLMObject
@property NSString * task;
@property NSString * description;
@property NSDate * dueDate;
...
@end
RLM_ARRAY_TYPE(Task) // define RLMArray<Task>
Then create a task list model as:
@interface TaskList : RLMObject
@property RLMArray<Task> * tasks;
@end
Now you create Task, add it to TaskList and save:
RLMRealm * realm = [RLMRealm defaultRealm];
[realm beginWriteTransaction];
Task * task = [Task new];
task.task = @"Some new task";
RLMArray <TaskList> * tasksLists = (RLMArray <TaskList> *)[TaskList allObjects];
// You can manage multiple task lists here using unique primary key for each task list. I am assuming that we have only one list.
TaskList * taskList = tasksLists.firstObject;
[taskList.tasks addObject: task];
[realm addOrUpdateObject: taskList];
[realm commitWriteTransaction];
Hope this helps.
Sorry I overlooked that you mentioned you are using Swift.
you first need to setup your models so that your todo's can be saved to the realm.
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()
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()
}