Query Realm get object which have particularly object in a list - ios

I think this is a simple solution, but i´m stuck with the best approach.
My Realm Database is made with the objects POI and CATEGORY. Where a POI can have one or multiple object of CATEGORY
class POI: Object {
dynamic var id:String = ""
dynamic var name:String = ""
dynamic var visited:Bool = false;
let categories = List<CATEGORY>()
override static func primaryKey() -> String?
{
return "id";
}
}
Later I need to show the number of POI that have a particular CATEGORY, and the number of POI that have a given CATEGORY with the boolean visited has true.
Something like this:
func getAllVisitedPointsWithCategory(idCategory:String) -> Results<POI> {
}
func getAllPointsWithCategory(idCategory:String) -> Results<POI>{
}
Any suggestion?

This should work:
func getAllVisitedPointsWithCategory(idCategory:String) -> [POI] {
let containingPOI = getAllPointsWithCategory(idCategory)
return containingPOI.filter({ (poi) -> Bool in
return poi.visited
})
}
func getAllPointsWithCategory(idCategory:String) -> [POI] {
let realm = try! Realm()
let containingPOI = realm.objects(POI).filter({ (poi) -> Bool in
return poi.categories.contains({ (cat) -> Bool in
return idCategory == cat.id
})
})
return containingPOI
}
It's basically just querying data and filtering the result.

This can be done more concisely and faster by using Realm's query engine rather than filtering the objects individually in Swift:
func getAllVisitedPointsWithCategory(idCategory:String) -> Results<POI> {
return getAllPointsWithCategory(idCategory).filter("visited = true")
}
func getAllPointsWithCategory(idCategory:String) -> Results<POI>{
let realm = try! Realm()
return realm.objects(POI.self).filter("ANY categories.id = %#", idCategory)
}

Related

Realm Swift duplicates item with primary key -> Threading problem?

I'm using ReamSwift to store data in my iOS application and I have troubles to figure out, why sometimes objects are duplicated in my application.
I use an UUID as primary key on every object. This property is defined in a base class and all the others are subclasses of that.
I use the update approach with a dictionary. So new objects are created and existing should be updated.
I use a central class which holds the Realm object and handles the update. This method could be called from multiple different threads.
This is my base class
import RealmSwift
open class RealmObject : Object {
static let ID_ATTRIBUTE : String = "id"
#objc dynamic var id : String = ""
override public static func primaryKey() -> String? {
return "id"
}
}
Central class managing swift.
This class holds the Realm Object
public var realm: Realm {
var tempRealm: Realm?
do {
tempRealm = try Realm(configuration: configuration)
}
catch let err {
print("------ERROR----- initializing realm\n \(err)")
}
if let tempRealm = tempRealm{
return tempRealm
}
return self.realm
}
This is the update method in the class. As a fallback if the id property is not set, it will be set as it is the primary key
func update<T: RealmObject>(_ obj : T, values : [String:Any?] ) -> T? {
var vals = values
do {
var res : T?
try realm.write {
if let idattr = vals[T.ID_ATTRIBUTE] as? String {
if(idattr.isEmpty) {
vals[T.ID_ATTRIBUTE] = UUID().uuidString
}
} else {
vals[T.ID_ATTRIBUTE] = UUID().uuidString
}
res = realm.create(T.self, value: vals, update: .modified)
}
return res
} catch {
return nil
}
}
Could calling the update method cause in any case the duplication as I set the primary key of the object? The problem is, I cannot reproduce to find the problem, i just encounter the issue from time to time and in the field from users.
One interesting thing, when a copy is deleted, also the other object will be deleted.
This is the method which deletes objects by id and type
func delete<T: RealmObject>(_ id : String, _ type : T.Type) -> Bool {
do {
let obj = get(id, T.self)
if let obj = obj {
try realm.write {
realm.delete(obj)
}
return true
} else {
return false
}
} catch {
return false
}
}

In realm When ever i am updating it is updating only in 0th index how to solve it?

in realm i given id = 0 and it is as primary key and it will be auto increment, but problem is while updating it is saving in the index path 0 as declare as id : Int = 0.
Where ever i update also it is only updating in 0th index only.
i want to update as per selected object.
What to do?
Program :-
class Discount: Object {
#objc dynamic var id : Int = 0
#objc dynamic var offerName : String = ""
#objc dynamic var percentage: Float = 0.00
#objc dynamic var segmentIndex : Int = 0
#objc dynamic var dateWise: Date?
override class func primaryKey() -> String? {
return "id"
}
//Incrementa ID
func IncrementaID() -> Int{
let realm = try! Realm()
if let retNext = realm.objects(Discount.self).sorted(byKeyPath: "id").last?.id {
return retNext + 1
}else{
return 1
}
}
}
Generally speaking, auto-incrementing primary keys are challenging to deal with and can cause headaches long term.
What's generally most important is ensuring primary keys are unique and using UUID strings is ideally suited for that.
class Discount: Object {
#objc dynamic var discount_id = UUID().uuidString
override static func primaryKey() -> String? {
return "discount_id"
}
}
There may be concern about ordering and often times that managed by either adding a class var to determine ordering; like a timestamp for example or if you want to preserve ordering, objects can be added to a List, which keeps the order, like an array.
To answer your specific question, the code in your question is not complete (it was partially pulled from another question). The reason is that for each object that's created, it must be written to realm first, then the next object's primary key is based on the prior object.
Here's an example.
#objcMembers class User: Object {
dynamic var uid: Int = 0
dynamic var username: String?
func getNextUid() -> Int {
let realm = try! Realm()
if let lastObject = realm.objects(User.self).sorted(byKeyPath: "uid").first {
let lastUid = lastObject.uid
let nextUid = lastUid + 1
return nextUid
}
return 1
}
override static func primaryKey() -> String? {
return "uid"
}
}
now the sequence to use this is as follows
let u0 = User()
u0.uid = u0.getNextUid()
u0.username = "User 0"
let realm = try! Realm()
try! realm.write {
realm.add(u0)
}
let u1 = User()
u1.uid = u1.getNextUid()
u1.username = "User 1"
try! realm.write {
realm.add(u1)
}
as you can see, each object needs to be written to realm in order to the next object to be queried to get the prior objects primary key.
It's a whole lot of potentially unnecessary work and code.
My advice: Stick with the UUID().uuidString for primary keys.

How to query List<Int> on Realm Swift

How can I filter out the RealmFilter.objectIds that has a given Int?
func delete(ids: [Int]) {
let filterResultsToDelete = realm.objects(CRMRealmFilterResult.self).filter("ANY objectIds IN %#",ids)
//Crashes
}
class RealmFilterResult : Object {
#objc dynamic var filterId: Int = 0
let objectIds = List<Int>()
override static func primaryKey() -> String {
return "filterId"
}
}
This may not be at all what you want but it was a good exercise. Maybe this will help.
Let me re-state what I think you're asking: You've got a series of objects that each have a List property of Int's and you want to be able to query for all objects that have a particular int in their list
Using a more real-world example, suppose we have a list of teams and we keep a list of game scores (a list) within each team
class TeamObject: Object {
#objc dynamic var object_id = NSUUID().uuidString
let scoreList = List<ScoreObject>()
override static func primaryKey() -> String? {
return "object_id"
}
}
and we have a score object that stores a score as an Int (and maybe other details like who they played or the date)
class ScoreObject: Object {
#objc dynamic var score = 0
let teamsWithScores = LinkingObjects(fromType: TeamObject.self, property: "scoreList")
}
For simplicity, let's create three scores and two teams and give each team two scores in their list.
let score1 = ScoreObject()
score1.score = 1
let score2 = ScoreObject()
score2.score = 2
let score3 = ScoreObject()
score3.score = 3
let t1 = TeamObject()
t1.scoreList.append(score1)
t1.scoreList.append(score3)
let t2 = TeamObject()
t2.scoreList.append(score2)
t2.scoreList.append(score3)
and write them to realm
try! realm.write {
realm.add(t1)
realm.add(t2)
}
from there, we can get any team that has a score of 1, which solves the question of getting the objects that have a list that contain a given int.
let results = realm.objects(ScoreObject.self).filter("score IN %#", [1])
if results.count > 0 {
for aScore in results {
let teamsWithThisScore = aScore.teamsWithScores
for team in teamsWithThisScore {
print("score: \(aScore.score)")
print(" id: \(team.object_id)")
}
}
} else {
print("no teams with those scores")
}
you can expand on this to get teams (object) that have several scores (ints)
let results = realm.objects(ScoreObject.self).filter("score IN %#", [1,3])
As I said, it may be off base but it does provide a solution in a more object oriented way.
Querying List of primitives (i.e. non Object subclasses, like Int in your case) is not yet supported by Realm.
You can follow the status of this on this GitHub issue.

Realm, Swift, Many-to-many relationship

On my API I've got a relationship between Stands and Products. In which stands have products, but products can be found in different stands aswell. I'm trying to replicate this relationship on my iOS-application, using Realm but I can't seem to get it working.
The goal of having this relationship is being able to search for Stands that sell particular products.
My model:
class Stand: Object {
dynamic var id : Int = 0
dynamic var name : String = ""
dynamic var latitude : Double = 0.0
dynamic var longitude : Double = 0.0
let products = List<Product>()
override static func primaryKey() -> String? {
return "id"
}
}
class Product: Object {
dynamic var id : Int = 0
dynamic var name : String = ""
let stands = List<Stand>()
override static func primaryKey() -> String? {
return "id"
}
}
When doing my API request for Stands I retrieve the associated Products with it aswell. When I append these to the Stands it works fine for my Stands model as the products are just normally added in the List().
But all of the products are individually created, without having any Stands attached to them.
Is there a way to directly assign these Stands to the Products upon creation of the Products? Just like it's happening the other way around?
My current solution is this..
func retrieveAndCacheStands(clearDatabase clearDatabase: Bool?) {
backend.retrievePath(endpoint.StandsIndex, completion: { (response) -> () in
let listOfProducts : List<(Product)> = List<(Product)>()
func addProducts(stand: Stand, products: List<(Product)>?) {
for product in products! {
print(product.name)
let newProduct = Product()
newProduct.id = product.id
newProduct.name = product.name
newProduct.stands.append(stand)
try! self.realm.write({ () -> Void in
self.realm.create(Product.self, value: newProduct, update: true)
})
}
listOfProducts.removeAll()
}
for (_, value) in response {
let stand = Stand()
stand.id = value["id"].intValue
stand.name = value["name"].string!
stand.latitude = value["latitude"].double!
stand.longitude = value["longitude"].double!
for (_, products) in value["products"] {
let product = Product()
product.id = products["id"].intValue
product.name = products["name"].string!
stand.products.append(product)
listOfProducts.append(product)
}
try! self.realm.write({ () -> Void in
self.realm.create(Stand.self, value: stand, update: true)
})
addProducts(stand, products: listOfProducts)
}
print(Realm.Configuration.defaultConfiguration.path!)
}) { (error) -> () in
print(error)
}
}
This stores the Stands and adds Products to them. It also creates all the products and adds 1 Stand per 10 ish Products (?).
I can't seem to figure out how to make this work. Does anyone else know how to solve this? Or a better solution?
Instead of doing the double-bookkeeping necessary to maintain inverse relationships manually, you should use Realm's inverse relationships mechanism, which provides you with all of the objects pointing to another object using a given property:
class Product: Object {
dynamic var id: Int = 0
dynamic var name: String = ""
// Realm doesn't persist this property because it is of type `LinkingObjects`
// Define "stands" as the inverse relationship to Stand.products
let stands = LinkingObjects(fromType: Stand.self, property: "products")
override static func primaryKey() -> String? {
return "id"
}
}
See Realm's docs on Inverse Relationships for more information.

How to determine if one array contains all elements of another array in Swift?

I have 2 arrays:
var list:Array<Int> = [1,2,3,4,5]
var findList:Array<Int> = [1,3,5]
I want to determine if list Array contains all findList elements.
By the way, elements might be String as well or other type.
How to do that?
I know that Swift provides contains method that works with one item.
Instead of iterating through arrays and doing filtering yourself, you can use NSSet to do all the work for you.
var list:Array<Int> = [1,2,3,4,5]
var findList:Array<Int> = [1,3,5]
let listSet = NSSet(array: list)
let findListSet = NSSet(array: findList)
let allElemtsEqual = findListSet.isSubsetOfSet(otherSet: listSet)
NSSet is a lot faster than arrays at checking if it contains any object. In fact it's what it's designed for.
Edit: Using Swift's built-in Set.
let list = [1,2,3,4,5]
let findList = [1,3,5]
let listSet = Set(list)
let findListSet = Set(findList)
//**Swift 4.2 and Above**
let allElemsContained = findListSet.isSubset(of: listSet)
//below versions
//let allElemsContained = findListSet.isSubsetOf(listSet)
allSatisfy seems to be what you want, assuming you can't conform your elements to Hashable and use the set intersection approach others have mentioned:
let containsAll = subArray.allSatisfy(largerArray.contains)
Since Swift 4.2 you can write:
extension Array where Element: Equatable {
func satisfy(array: [Element]) -> Bool {
return self.allSatisfy(array.contains)
}
}
Otherwise for Swift 3, Swift 4 you can write this:
extension Array where Element: Equatable {
func contains(array: [Element]) -> Bool {
for item in array {
if !self.contains(item) { return false }
}
return true
}
}
You can see the:
contains method here
allSatisfy method here
This is just a simple extension that check if the array that you give is in the current array (self)
You can use the filter method to return all elements of findList which are not in list:
let notFoundList = findList.filter( { contains(list, $0) == false } )
then check if the length of the returned array is zero:
let contained = notFoundList.count == 0
Note that his solution traverses the entire findList array, so it doesn't stop as soon as a non contained element is found. It should be used if you also want to know which elements are not contained.
If you just need a boolean stating whether all elements are contained or not, then the solution provided by Maxim Shoustin is more efficient.
Consider following generic method:
func arrayContainsArray<S : SequenceType where S.Generator.Element : Equatable>
(src:S, lookFor:S) -> Bool{
for v:S.Generator.Element in lookFor{
if contains(src, v) == false{
return false
}
}
return true
}
The advantage - method stops after 1st fail and do not continue over findList
Tests
var listAsInt:Array<Int> = [1,2,3,4,5]
var findListAsInt:Array<Int> = [1,3,5]
var result = arrayContainsArray(listAsInt, findListAsInt) // true
listAsInt:Array<Int> = [1,2,3,4,5]
findListAsInt:Array<Int> = [1,3,5,7,8,9]
result = arrayContainsArray(listAsInt, findListAsInt) // false
var listOfStr:Array<String> = ["aaa","bbb","ccc","ddd","eee"]
var findListOfStr:Array<String> = ["bbb","ccc","eee"]
result = arrayContainsArray(listOfStr, findListOfStr) // true
listOfStr:Array<String> = ["aaa","bbb","ccc","ddd","eee"]
findListOfStr:Array<String> = ["bbb","ccc","eee","sss","fff","ggg"]
result = arrayContainsArray(listOfStr, findListOfStr) // false
(tested on Beta7)
As a complement to Sequence.contains(element) handling multiple elements, add this extension:
public extension Sequence where Element : Hashable {
func contains(_ elements: [Element]) -> Bool {
return Set(elements).isSubset(of:Set(self))
}
}
Used:
list.contains(findList)
Since this uses Set/Hashable it performs much better than Equatable alternatives.
Right now, I'd probably use something like:
let result = list.reduce(true, { $0 ? contains(findList, $1) : $0 })
...but then I did just read this article, which might be biasing me towards this kind of solution. You could probably make this more efficient without making it completely unreadable, but it's early and I've not had my coffee.
Extend the Array with the following methods:
extension Array {
func contains<T where T : Equatable>(obj: T) -> Bool {
return self.filter({$0 as? T == obj}).count > 0
}
func isEqualTo< T : Equatable> (comparingArray : [T]) -> Bool {
if self.count != comparingArray.count {
return false
}
for e in comparingArray {
if !self.contains(e){
return false
}
}
return true
}
}
An example of how you can use it like this:
if selectedDates.isEqualTo(originalDates) {
//Arrays the same hide save button
} else {
//Arrays not the same, show Save & Discard Changes Button (if not shown)
}
Shout out to #David Berry for the contain method.
None of the previous answers seem to be right.
consider:
let a = [2,2]
let b = [1,2,3]
we wouldn't say that b actually "contains" a, but if your algorithm is based on for-loop & swift's built-in contains(element:) or a set, the above case would pass.
I use this set of extended methods myself. I hope this code snippet helps:
// Array + CommonElements.swift
import Foundation
public extension Array where Element: Hashable {
func set() -> Set<Array.Element> {
return Set(self)
}
func isSubset(of array: Array) -> Bool {
self.set().isSubset(of: array.set())
}
func isSuperset(of array: Array) -> Bool {
self.set().isSuperset(of: array.set())
}
func commonElements(between array: Array) -> Array {
let intersection = self.set().intersection(array.set())
return intersection.map({ $0 })
}
func hasCommonElements(with array: Array) -> Bool {
return self.commonElements(between: array).count >= 1 ? true : false
}
}
This is Maxim Shoustin's answer updated for Swift 3:
func arrayContainsArray<S : Sequence>
(src:S, lookFor:S) -> Bool where S.Iterator.Element : Equatable{
for v:S.Iterator.Element in lookFor{
if src.contains(v) == false{
return false
}
}
return true
}
If you need to determine, that one array is subArray of another.
public extension Array where Element: Equatable {
func isSuperArray(of array: Array<Element>) -> Bool {
guard
count >= array.count,
let indexes = array.first.flatMap(indexes(of:)),
!indexes.isEmpty else {
return false
}
let arraysForComparison = indexes
.compactMap { index -> [Element]? in
guard index + (array.count - 1) <= count else { return nil }
return Array(self[index..<(index + array.count)])
}
return arraysForComparison.contains(array)
}
func isSubArray(of array: Array<Element>) -> Bool {
array.isSuperArray(of: self)
}
private func indexes(of element: Element) -> [Index] {
enumerated()
.filter { element == $0.1 }
.map { index, _ in index }
}
}
Example of usage:
let array1 = [1, 2, 3, 4]
let array2 = [2, 3]
print(array1.isSuperArray(of: array2)) // true
print(array2.isSubArray(of: array1)) // true
print(array2.isSuperArray(of: array1)) // false
print(array1.isSubArray(of: array2)) // false

Resources