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
Target Parameter in Dispatchqueue
Wkwebview Notification When View Is Actually Shown
How to Detect That Parameter Is a Tuple of Two Arbitrary Types
How to Fix 'Line Length Violation: Line Should Be 120 Characters or Less' - Swiftlint
Asyncdetached Falling Back into Main Thread After Mainactor Call
Convert Firdatasnapshot to Custom Type
How to Work with Bindings When Using a View Model VS Using @Binding in the View Itself
How to Get Day and Month from Date Type - Swift 4
How to Bind a Variable to Multiple Alternatives in a Switch Statement
Lazy Readonly Property in Swift
How to Set Uisegmentedcontrol Tint Color for Individual Segment
Aws S3 Transfer Manager ${Cognito-Identity.Amazonaws.Com:Sub} Policy Variable Access Denied