Skip to content

Instantly share code, notes, and snippets.

@29satnam
Last active February 7, 2022 04:27
Show Gist options
  • Save 29satnam/b683a9e2407574723e84df1bbf61bb0e to your computer and use it in GitHub Desktop.
Save 29satnam/b683a9e2407574723e84df1bbf61bb0e to your computer and use it in GitHub Desktop.
Realm CRUD Swift 5
import UIKit
import RealmSwift
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let realm = try! Realm()
// Save
let note = Note()
note.id = incrementID()
note.title = "Remember the milk!"
note.text = "Mom asked if I could bring a gallon of milk home."
try! realm.write {
realm.add(note)
}
// Retrieve
let notes = realm.objects(Note.self)
for note in notes {
print("title:", note.title)
print("text:", note.text)
}
// Update
let objects = realm.objects(Note.self).filter("title = %@", "Remember the milk!")
if let object = objects.first {
try! realm.write {
object.text = "updatedtext"
object.title = "updatetitle"
}
}
// Delete
if let userObject = realm.objects(Note.self).filter("id == 2").first {
print("In process of deleting")
try! realm.write {
realm.delete(userObject)
}
print("Object deleted.")
}
else{
print("Object not found.")
}
}
// Simple Incremental ID
func incrementID() -> Int {
let realm = try! Realm()
return (realm.objects(Note.self).max(ofProperty: "id") as Int? ?? 0) + 1
}
}
class Note: Object {
@objc dynamic var id = 0
@objc dynamic var title = ""
@objc dynamic var created = Date()
@objc dynamic var text = ""
override static func primaryKey() -> String? {
return "id"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment