How to use RLMArray to save an Array

前端 未结 2 951
温柔的废话
温柔的废话 2021-01-12 20:03

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

2条回答
  •  旧时难觅i
    2021-01-12 20:44

    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
    

    Then create a task list model as:

    @interface TaskList : RLMObject
    
    @property RLMArray * 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  * tasksLists = (RLMArray  *)[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.

提交回复
热议问题