I'm new in programming and I would like to know how I can store data in a List with RealmSwift.
Considering the following model:
import RealmSwift
class ScanResults: Object{
dynamic var id = 0
dynamic var resource = ""
dynamic var scanDate = ""
let ScanResultsDetail = List<ScanResultsDetails>()
}
class ScanResultsDetails: Object{
dynamic var scanner = ""
dynamic var result = ""
}
This is an example how I store new ScanResults:
let newResults = ScanResults()
newResults.id = newResults.IncrementaID()
newResults.resource = "Test"
newResults.scanDate = "19.01.2016"
do{
try uiRealm.write({ () -> Void in
uiRealm.add(newResults)
})
}
catch{
}
My Question is now, how can I store data in the list? I can't figure it out.. Can you give me an example?
I don't see that you append any object to ScanResultsDetail in your example
Here is quick example based on swift source code (docs):
class Dog: Object {
dynamic var name = ""
dynamic var age = 0
}
class Person: Object {
dynamic var name = ""
let dogs = List<Dog>()
}
let realm = try! Realm() // Create realm pointing to default file
// Link objects
let person = Person()
person.name = "Tim"
person.dogs.append(mydog)
try! realm.write {
realm.add(person)
}
Related
I am learning to develop on Swift, so sorry if my questions seem stupid :D
On my app, I need 3 objects : Car, Station & Conso
A Car Object can have many Conso
A Station Object car have many Conso
A Conso Object can be linked to only one Car and one Station
Here are the codes for Realm objects
Conso.swift
import Foundation
import RealmSwift
final class Conso : Object {
//var id: Int
#objc dynamic var idConso = ""
//... Some fields
#objc dynamic var data: NSData?
#objc dynamic var idCar = ""
#objc dynamic var station: Station? // Link to a Station Object
#objc dynamic var car: Car? // Link to a car Object
Car.swift
import Foundation
import RealmSwift
final class Car : Object {
//#objc dynamic var ID = 0
#objc dynamic var idCar = ""
//...some fields
#objc dynamic var data: NSData?
// Link to Conso object (Many-to-One)
let consos = LinkingObjects(fromType: Conso.self, property: "car")
Station.swift
import Foundation
import RealmSwift
import MapKit
final class Station : Object {
//#objc dynamic var ID = 0
#objc dynamic var idStation = ""
//...some fields
#objc dynamic var data: NSData?
// Link to Conso object (Many-to-One)
let consos = LinkingObjects(fromType: Conso.self, property: "station")
I insert the objects on database using this snippet :
// Create a Conso Object
let conso:Conso = Conso()
conso.idConso = "Conso-123454344"
if let textStationService = self.TextFieldStationService.text{
conso.nomStation = textStationService
conso.station?.nomStation = textStationService
}
if let textCPStationService = self.TextFieldCodePostal.text{
conso.CPStation = textCPStationService
self.station!.codePostal = textCPStationService
}
if let textVilleStationService = self.TextFieldStationServiceCPVille.text{
conso.villeStation = textVilleStationService
self.station!.ville = textVilleStationService
}
// A car object is received from another viewController
conso.car = self.car
let realm = try! Realm()
try! realm.write {
realm.add(conso)
realm.add(station!)
}
From another ViewController, I get the results with this snippet
assumed that a car id (idCar) is received from another VC :
func listConso(){
let realm = try! Realm()
// Get the car from its id
self.car = realm.objects(Car.self).filter("idCar = %#",self.idCar).first
// Get Conso based on the searched car
self.consosData = realm.objects(Car.self).filter("idCar = %#",self.idCar).first?.consos.sorted(byKeyPath: "dateConso", ascending: false)
self.consos = Array((self.consosData)!)
self.tableViewConso.setEditing(false, animated: true)
self.tableViewConso.reloadData()
print("listConsop")
}
The result is that I have many lines twice
Thank you for your help.
I am getting JSON data from server by api call in swift application.
So, I want to store that into Realm data base and again need to fetch to show in tableview.
I have no idea about Realm database, After, checked few forums, I got basic idea for creating Object class.
So, I have installed Realm pod file and imported that library to my classes.
My JSON data is
[{
"type": "story",
"story":
{
"author-name": "",
"headline": "Quotes ",
"summary": "Best quotes of Muhammad Ali",
"hero-image": "https://image”
}
},
{
"type": “Trending”,
"story":
{
"author-name": "",
"headline": "Quotes ",
"summary": "Best quotes of Muhammad Ali",
"hero-image": "https://image”
}
},
{
"type": “Technology”,
"story":
{
"author-name": "",
"headline": "Quotes ",
"summary": "Best quotes of Muhammad Ali",
"hero-image": "https://image”
}
},
{
"type": “Top”,
"story":
{
"author-name": "",
"headline": "Quotes ",
"summary": "Best quotes of Muhammad Ali",
"hero-image": "https://image”
}
}
]
And I have each type keyword has different model class saved data from api data to show in Tableview
like
let storyObj = StoryModule()
let trending = StoryModule()
let technology = StoryModule()
let stotopryObj1 = StoryModule()
and I am saving each key value for every type
if abc.type == "story" {
let storyObj = abc.story
storyObj.authorname = storyObj?.authorname
storyObj.heroimage = storyObj?.heroimage
storyObj.headline = storyObj?.headline
storyObj.summary = storyObj?.summary
self.treningStoriesList.append(storyObj)
}
It is same for remaining Trending, Top and Technology objects.
and the Realm module is
import RealmSwift
class DemoInfo: Object {
#objc dynamic var category = ""
let items = List<DemoList>()
}
class DemoList : Object {
#objc dynamic var authorName = ""
#objc dynamic var imageUrl = ""
#objc dynamic var summary = ""
#objc dynamic var headLine = ""
}
And In MainViewController class,
let realmDB = try! Realm()
But, Here I got struck, How to save those storyObj,technology,top, etc module data and fetch.
Can anyone suggest me?
If you want to add a realm object in your db, you must define a primary key for each realm object classes. So, you need to change your JSON file, after you can create your realm objects like this;
DemoObject.swift
import RealmSwift
class DemoObject: Object {
#objc dynamic var id: String = ""
#objc dynamic var type: String = ""
#objc dynamic var subObject: SubObject?
override static func primaryKey() -> String? {
return "id"
}
}
SubObject.swift
import RealmSwift
class SubObject: Object {
#objc dynamic var id: String = ""
#objc dynamic var authorName: String = ""
#objc dynamic var imageUrl: String = ""
#objc dynamic var summary: String = ""
#objc dynamic var headLine: String = ""
override static func primaryKey() -> String? {
return "id"
}
}
Then, you can use these codes to add your db.
let realm = try! Realm()
let demo = DemoObject()
demo.id = "1"
let sub = SubObject()
sub.id = "1"
sub.authorName = "Author Name"
sub.headLine = "Head Line"
sub.summary = "image Url"
demo.subObject = sub
try! realm.write {
realm.add(demo, update: true)
}
I Have one class UserObject(Object) that has one property of SessionObject(Object), and the SessionObject has properties of other Realm Objects(TestObject, NewObject).
When I delete the children Objects and after that the parent Object successfully, the app crashes with Bad Access: EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
class UserObject: Object{
dynamic var uuid = ""
dynamic var username = ""
dynamic var session: SessionObject?
class SessionObject: Object{
dynamic var tokenType = ""
dynamic var refreshToken = ""
dynamic var test: TestObject?
dynamic var new: NewObject?
}
class TestObject: Object{
dynamic var test = ""
}
class NewObject: Object{
dynamic var test = ""
}
func deleteUser(){
guard let realm = self.realmInstance else{
return
}
guard let user = Array(realm.objects(UserObject.self)).first else{
return
}
do{
try realm.write {
if let session = user.session{
if let test = session.test{
realm.delete(test)
}
if let new = session.new{
realm.delete(new)
}
realm.delete(session)
}
realm.delete(user)
}
}catch{
}
}
You're running in to ARC naming conventions, which apply to dynamic properties on Swift classes. Currently Realm does not generate accessor methods which conform to what ARC expects for specially-named methods, which results in objects being double-deleted when you have a property name starting with new, copy or mutableCopy.
I have some Realm classes that look like this:
class Friends: Object {
dynamic var name = true
dynamic var role = true
dynamic var type = true
dynamic var owner: Profile?
}
class Profile: Object {
dynamic var uuid = NSUUID().UUIDString
dynamic var name = ""
dynamic var date = NSDate(timeIntervalSinceNow: 1)
dynamic var section = 0
dynamic var code = ""
dynamic var gender = 0
dynamic var type = ""
let friends = List<Friends>()
override static func primaryKey() -> String? {
return "uuid"
}
}
class Sub: Profile {
dynamic var owner: Master?
}
class Master: Object {
dynamic var type = ""
dynamic var name = ""
dynamic var date = ""
let subs = List<Sub>()
}
I understand that to retrieve the objects from realm I have to do this:
var master = try! Realm().objects(Master)
let profile = master[indexPath.row]
let date = profile.date
let name = profile.name
let type = profile.type
The question is: How do I retrieve objects from the 'subs'(List) ?
When you retrieve a master object you can access its subs list like any other property:
let subs = profile.subs
This gives you a list that you can iterate over:
for sub in profile.subs {
// do something with the sub object
}
Or you can filter the subs to find a particular object:
if let subjectWithId = profile.subs.filter("uuid == '7382a8d83'").first {
// do something with the subject
}
Or you can use subscripting to access elements by index:
let secondProfile = profile.subs[1]
My class has all properties as dynamic but still when retrieving them from realm i get a collection of empty objects, and check the realm db with the realm browser and the data is there, this is my class:
class ProjectEntity: Object {
/**
Property: All properties of the ProjectEntity
**/
dynamic var ProjectId = 0
dynamic var ProjectTitle = ""
dynamic var ProjectSubtitle = ""
dynamic var ProjectType = ""
dynamic var ProjectClass = ""
dynamic var ProjectCoordinates = ""
dynamic var ProjectGraphType = ""
dynamic var ProjectModifiedOn = NSDate(timeIntervalSince1970: 0)
dynamic var ProjectCity = ""
dynamic var ProjectCounty = ""
dynamic var ProjectZip = ""
override static func primaryKey() -> String? {
return "ProjectId"
}
func getShape() -> MapShape{
let adapter = ProjectsJSONAdapter()
let shape: MapShape = adapter.parseShape(id: self.ProjectId, type: self.ProjectGraphType, jsonStr: self.ProjectCoordinates)
return shape
}
}
here is how i'm reading the data:
let projectsList = realm.objects(ProjectEntity)
for project in projectsList {
projects.append(project)//The properties in project have all their default/empty values
}
any ideas?
How are you retrieving the persisted ProjectEntity objects? The following code snippet should do the trick:
let entities = Realm().objects(ProjectEntity)
first your class need to inherit RLMObject :
class ProjectEntity: RLMObject {
...
}
and after if you want all the ProjectEntity objects try this :
let allProjectEntityObjects: RLMResults = ProjectEntity.allObjects()
if you need some extra help you can follow this tutorial from Realm :
Building a To-Do App with Realm