iOS - RealmSwift - ios

I have created in my application to the database using Realmsvift. Here is the output in the console. Please tell me, how do I read data from it in the application? For example, I want to display key-values: Oslo - 2.89. Thanks for the help.
class ViewController: UIViewController {
var city_list: [String] = ["Moscow", "London", "Oslo", "Paris"]
let realm = try! Realm()
override func viewDidLoad() {
super.viewDidLoad()
let manager: ManagerData = ManagerData()
for name in city_list {
manager.loadJSON(city: name)
}
let localWeather = realm.objects(WeatherData.self)
print(localWeather)
/////////////////////////////////////////
Results<WeatherData> (
[0] WeatherData {
city_name = Moscow;
tempList = RLMArray <0x6080002e2b00> (
[0] Temp {
temp = -4.25;
}
);
},
[1] WeatherData {
city_name = London;
tempList = RLMArray <0x6000002e4700> (
[0] Temp {
temp = 9.630000000000001;
}
);
},
[2] WeatherData {
city_name = Paris;
tempList = RLMArray <0x6000002e4800> (
[0] Temp {
temp = 6.59;
}
);
},
[3] WeatherData {
city_name = Oslo;
tempList = RLMArray <0x6000002e4900> (
[0] Temp {
temp = -2.89;
}
);
}

If I understand your question correctly, you want to get properties from each model.
If that is the case, you're almost there. localWeather is like an array in the Realm's world (e.g., type of Results<WeatherData>).
You can just access it like normal swift's array/objects:
let firstWeather = localWeather[0]
let name = firstWeather.city_name
let temp = firstWeather.tempList[0].temp
// do what you want with 'name' and 'temp', e.g. key-value
print("\(name) - \(temp)")

Related

How to sort by comparing with each characters in swift?

Sorry, I have a question about sort data.
I don't know how to sort each characters , I just sort by first characters like following image.
How can I sort characters in each section array.
Thanks.
var cityCollation: UILocalizedIndexedCollation? = nil
var sectionsCityArray = [[City]]()
var cityArray:[City] = [City]() //cityArray is my original data that is not sorting
func configureSectionCity() {
cityCollation = UILocalizedIndexedCollation.current()
let sectionTitlesCount = cityCollation!.sectionTitles.count
var newSectionsArray = [[City]]()
for _ in 0..<sectionTitlesCount {
let array = [City]()
newSectionsArray.append(array)
}
for bean in cityArray {
let sectionNumber = cityCollation?.section(for: bean, collationStringSelector: #selector(getter: City.name))
var sectionBeans = newSectionsArray[sectionNumber!]
sectionBeans.append(bean)
newSectionsArray[sectionNumber!] = sectionBeans
}
sectionsCityArray = newSectionsArray
}
Assuming the City object has a name property and you want the order q001, q002, q004, q005, q010, q012 you could use
newSectionsArray[sectionNumber!] = sectionBeans.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }
localizedStandardCompare requires the Foundation framework

How to search an element in Array of Dictionary?

Below mentioned is my array. I need to check if the barcode 8901058847857 or barcode xxxxxxxxxxx exists in array or not.
(
{
barcode = 8901058847857;
image = (
);
name = "Maggi Hot Heads";
productTotal = "60.00";
quantity = 3;
},
{
barcode = 8901491101837;
image = (
);
name = "Lays Classic Salted";
productTotal = "20.00";
quantity = 1;
}
)
I tried using array.contains or array.elements but it is not working because barcode exists in an array.
** Try this **
// Put your key in predicate that is "barcode"
var namePredicate = NSPredicate(format: "barcode contains[c] %#",searchString);
let filteredArray = arrayOfDict.filter { namePredicate.evaluate(with: $0) };
print("names = ,\(filteredArray)")
You can search your array of dictionaries using contains where but you need to cast your value from Any to Int before trying to compare them:
if array.contains(where: {$0["barcode"] as? Int ?? 0 == 8901058847857}) {
print(true)
}
You can also run for loop to check the presence of element in your Array of dictionary.
let DictnaryArray = (
{
barcode = 8901058847857;
image = (
);
name = "Maggi Hot Heads";
productTotal = "60.00";
quantity = 3;
},
{
barcode = 8901491101837;
image = (
);
name = "Lays Classic Salted";
productTotal = "20.00";
quantity = 1;
}
)
for (index,element) in DictnaryArray{
let dict = DictnaryArray[index]
if dict["barcode"] == 8901058847857 || dict["barcode"] == XXXXXXXXXXX{
print("BarCode Exist")
print("\(dict["barcode"])")
}
}
Hope it helps!

Multidimensional Array in Realm Swift (Maximum depth exceeded error)

I want to make a 3D Array with Realm and I use List to accomplish this.
This is the code for my RealmDatabase:
class Sensors : Object {
dynamic var type = ""
dynamic var name = ""
let buttonAr = List<buttons>()
}
class buttons: Object{
let buttonsAdded = List<objectNameTopic>()
}
class objectNameTopic: Object {
dynamic var name = ""
dynamic var topic = ""
}
And this is what I use to call it:
var saving = Sensors()
var saving2 = objectNameTopic()
var but = buttons()
var array = ["on", "off"]
var array2 = ["1","2"]
var allSensors = useOfRealm.objects(Sensors.self)
override func viewDidLoad() {
super.viewDidLoad()
addSensor()
for i in 0...array.count-1 {
addSensor2(name: array[i], topic: array2[i])
}
if allSensors.count > 0 {
print(allSensors)
}
}
func addSensor() {
try! useOfRealm.write {
saving.type = "topic1"
saving.name = "mike"
useOfRealm.add(saving)
}
}
func addSensor2(name: String, topic: String) {
try! useOfRealm.write {
saving2.name = name
saving2.topic = topic
useOfRealm.add(saving2)
but.buttonsAdded.append(saving2)
saving.buttonAr.append(but)
}
}
This is what I get when I print the results:
Results<Sensors> (
[0] Sensors {
type = topic1;
name = mike;
buttonAr = RLMArray <0x6100000fd900> (
[0] buttons {
buttonsAdded = RLMArray <0x6100000fdb00> (
[0] <Maximum depth exceeded>,
[1] <Maximum depth exceeded>
);
},
[1] buttons {
buttonsAdded = RLMArray <0x6180000fd180> (
[0] <Maximum depth exceeded>,
[1] <Maximum depth exceeded>
);
}
);
}
)
Any Ideas of what I'm missing?
Thanks in advance
If the <Maximum depth exceeded> in the XCode console output is what you fear, fear no more. It's just a way the console is telling you that the object hierarchy is too deep for showing it to you, but the object(s) are there accessible through code.
Just try to print the content of your result by iterating through it and printing each child object instead of printing only the root.

How to Sort an array in an ascending order swift 2.3

[{
msg = "Hi This is Jecky";
name = Susheel;
sender = 77;
timestamp = 1464241769520;
username = susheel;
}, {
msg = Dubai;
name = Jecky;
sender = 78;
timestamp = 1464246547147;
username = Jecky;
}, {
msg = "How are you ?";
name = Susheel;
sender = 77;
timestamp = 1464243480381;
username = susheel;
}, {
msg = "Aje dekhai nai";
name = Jecky;
sender = 78;
timestamp = 1464244974198;
username = Jecky;
}]
I have an array like this. I want to sort this array using timestamp in swift 2.3 or latest version of swift. Can anyone help me for this ?
let array=[
[
"msg":"Hi This is Jecky",
"name":"Susheel",
"sender":77,
"timestamp":1464241769520,
"username":"susheel",
],
[
"msg":"Dubai",
"name":"Jecky",
"sender":78,
"timestamp":1464246547147,
"username":"Jecky",
],
[
"msg":"How are you ?",
"name":"Susheel",
"sender":77,
"timestamp":1464243480381,
"username":"susheel",
],
[
"msg":"Aje dekhai nai",
"name":"Jecky",
"sender":78,
"timestamp":1464244974198,
"username":"Jecky",
],
]
print("array = \(array)")
let sortedArray=array.sort { (obj1, obj2) -> Bool in
return (obj1["timestamp"] as! Double) < (obj2["timestamp"] as! Double)
}
print("sortedArray = \(sortedArray)")
If your array is mutable you can user sortInPlace
yourArray.sortInPlace{$0.timestamp < $1.timestamp}
and if not, you can create a new array from sort, like suggested by Kristijan (although no need for parentheses on trailing closures):
let newArray = yourArray.sort{$0.timestamp < $1.timestamp}
You can get this functionality using extension:
extension NSArray{
//sorting- ascending
func ascendingArrayWithKeyValue(key:String) -> NSArray{
let ns = NSSortDescriptor.init(key: key, ascending: true)
let aa = NSArray(object: ns)
let arrResult = self.sortedArray(using: aa as! [NSSortDescriptor])
return arrResult as NSArray
}
//sorting - descending
func discendingArrayWithKeyValue(key:String) -> NSArray{
let ns = NSSortDescriptor.init(key: key, ascending: false)
let aa = NSArray(object: ns)
let arrResult = self.sortedArray(using: aa as! [NSSortDescriptor])
return arrResult as NSArray
}
}
use like this:
let array=[
[
"msg":"Hi This is Jecky",
"name":"Susheel",
"sender":77,
"timestamp":1464241769520,
"username":"susheel",
],
[
"msg":"Dubai",
"name":"Jecky",
"sender":78,
"timestamp":1464246547147,
"username":"Jecky",
],
[
"msg":"How are you ?",
"name":"Susheel",
"sender":77,
"timestamp":1464243480381,
"username":"susheel",
],
[
"msg":"Aje dekhai nai",
"name":"Jecky",
"sender":78,
"timestamp":1464244974198,
"username":"Jecky",
],
]
let a = NSArray.init(array: array)
let filArray = a.ascendingArrayWithKeyValue(key: "timestamp")
print(filArray)
customArray.sortInPlace {
(element1, element2) -> Bool in
return element1.someSortableField < element2.someSortableField
}
Check this out
https://www.hackingwithswift.com/example-code/arrays/how-to-sort-an-array-using-sort
To sort by property "timestamp"
array.sorted{$1["timestamp"] as? Long > $0["timestamp"] as? Long}
=> First, convert your Json to Objects. (check this link to do that :- http://roadfiresoftware.com/2015/10/how-to-parse-json-with-swift-2/ )
=> Then declare your Array as a typed array so that you can call methods when you iterate:
var array : [yourObjectClassName] = []
=> Then you can simply sort the value by :
array.sort({ $0.name > $1.name })
The above example sorts all the arrays by name. If you need to sort by timeStamp you can change the name to timeStamp ..etc
Check this link for more sorting examples : Swift how to sort array of custom objects by property value

Realm queries to extract data

I have 2 Realm Models:
class CourseModel: Object {
dynamic var coursename = ""
dynamic var par3field = 0
dynamic var par4field = 0
dynamic var par5field = 0
let scoreModels: List<ScoresModel> = List<ScoresModel>()
override internal static func primaryKey() -> String? { return "coursename" }
}
class ScoresModel: Object {
dynamic var dateplayed = ""
var courseModel: CourseModel? {
return linkingObjects(CourseModel.self, forProperty: "scoreModels").first
}
}
The app user will first add a new course for which I use CourseModel. As the user plays a course they enter scores for that course, for which I use ScoresModel, hence the primary key 'coursename'.
I query the CourseModel with
let realm = try Realm()
let results = realm.objects(CourseModel)
return results
and it produces the following result
Results<CourseModel> (
[0] CourseModel {
coursename = First Course;
par3field = 4;
par4field = 10;
par5field = 4;
scoreModels = RLMArray <0x797a36d0> (
[0] ScoresModel {
dateplayed = Apr 5, 2016; },
[1] ScoresModel {
dateplayed = Mar 3, 2016; }
);
},
[1] CourseModel {
coursename = Second Course;
par3field = 4;
par4field = 10;
par5field = 4;
scoreModels = RLMArray <0x7a046f40> (
[0] ScoresModel {
dateplayed = Apr 5, 2016; }
);
}
)
The ScoresModel produces a similar result but without the CourseModel data.
The ScoresModel has a lot of data in it, I only showed 'dateplayed' here to keep it short.
My question is this; when I've extracted the data from Realm how can I access a particular field to work with that data, i.e. how do I get the par5field data to do calculations with it, and also the 2nd question how do I get to the scoreModels data, for example 'dateplayed' to list the dates in a table for example?
When you perform a query against Realm, the results are returned in a Results object that behaves exactly like an array. So you need to iterate through each object to access the properties you want for each one.
To answer your first question, to access the par5field property (From just the first object):
let firstObject? = results.first
let par5field = firstObject.par5field
// Do calculations with it
For your second question, scoreModels is just a standard array object, so you can just insert the values it into a table view as you would a standard Array object.
If you wanted to list ALL of the ScoreModel objects, regardless of which CourseModel objects they belong to, you can perform a Realm query to get them directly.
let realm = try! Realm()
let results = realm.objects(ScoreModel)
return results

Resources