Saving Array to Realm in Swift

saving array into realm database swift

To be able to store several objects of type Data in a single property of an Object subclass, you need to use List.

class TodoListModel: Object {

@objc dynamic var id = UUID().uuidString
@objc dynamic var createdDate: Date?
let photos = List<Data>()
let parentCategory = LinkingObjects(fromType: CategoryModel.self, property: "items")

override static func primaryKey() -> String? {
return "id"
}

}

Then you can create a TodoListModel instance like this:

func createTodoList(createdDate: Date, photos: Array<Data>? = nil) -> Void {
let todoList = TodoListModel()
todoList.createdDate = createdDate
if let photos = photos {
todoList.photos.append(objectsIn: photos)
}
TodoListFunctions.instance.addData(object: todoList)
}

Store array of String in Realm

You cannot store Swift Array to Realm store. Instead of using Array you could make it List<String>. And you can use append(objectsIn:) method.

class Reminder: Object {
@objc dynamic var name = ""
@objc dynamic var done = false
let namesArray = List<String>()
}

Then, simply append new items to the list like this,

let names : [String] = ["Ali","Hammad","Hamza"]
let textFieldReminder = (alertVC.textFields?.first)! as UITextField

let reminderItem = Reminder() // (8)
reminderItem.name = textFieldReminder.text!
reminderItem.done = false
reminderItem.append(objectsIn: names)

How to save a JSON array to Realm in Swift?

save(todoItem: listArray) doesn't work because save expects an [Object], but listArray is a [TodoListResponse].

What you are missing is the step that converts your codable struct TodoListResponse to the Realm model TodoIItemList. I would write the save method like this:

func save(_ todoListResponses: [TodoListResponse]) {
do{
try realm.write{
for response in todoListResponses {
let object = TodoIItemList()
object.title = response.title
object.completed = response.completed
realm.add(object)
}
}
}catch{
print(error)
}
}

Now save(todoItem: listArray) should work.

If there are many properties that needs to be set in TodoIItemList, you can move the "copying properties" logic to a convenience initialiser of TodoIItemList that initialises a TodoIItemList from a TodoListResponse.



Related Topics



Leave a reply



Submit