Predicate in realm with dictionary parameters - swift

I want to create a predicate with a dictionary paramateres and filter data on realm, like
var parameters = [String: Any]()
parameters["Mobile"] = a.Mobile!
parameters["CategoryId"] = self.SelectCategryId
let existContact = (contactBiz.FetchMulti(parameters: parameters)?.count)! > 0
and in fetchMulti func I make a predicate and filter data
func FetchMulti(parameters: [String: Any])-> Results<RealmEntityType>?
{
do
{
let key = T.KeyName()
var object = realm.objects(RealmEntityType.self)
let subPredicates = parameters.map {
NSPredicate(format: "%# = %#", $0.key, $0.value as! CVarArg)
}
let compoundPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: subPredicates)
// var predictionArray = [String]()
// for p in parameters
// {
// predictionArray.append("\(p.key) = \(p.value) ")
//
// }
//
// let perdicate = predictionArray.joined(separator: " && ")
//
return object.filter(compoundPredicate);
}
catch
{
print(error.localizedDescription)
}
return nil
}
but I get this error
reason: 'Predicate expressions must compare a keypath and another keypath or a constant value'
Any help!

You need to use %K to indicate that the value is the name of a key and not a constant string: NSPredicate(format: "%K = %#", $0.key, $0.value as! CVarArg)

Related

Swift Core Data - handling empty fetch result

I have a simple entity, a stationID and a type, both Strings
I use this method to search for a type for a given stationID,
func returnStationType(stationTypeId: String) -> PersistantStationType {
let context = container.viewContext
let request = PersistantStationType.fetchRequest() as NSFetchRequest<PersistantStationType>
request.predicate = NSPredicate(format: "%K == %#", #keyPath(PersistantStationType.stationId), stationTypeId as CVarArg)
do {
let result = try context.fetch(request)
if result.count != 0 {
let fetchedStationType = result.first!
return fetchedStationType
} else { print("4 Fetch result was empty for specified stationid: \(String(describing: stationTypeId))")
}
} catch { print("Fetch on goal id: \(String(describing: stationTypeId)) failed. \(error)") }
return PersistantStationType.init()
}
I call the method here:
let persistentStationType = persistenceController.returnStationType(stationTypeId: closestStation.id)
let stationType = persistentStationType.type?.lowercased().capitalized
let realName = helper.returnRealName(stationType: stationType ?? "None")
let imageName = helper.returnStationTypeImage(stationType: stationType ?? "None")
If a stationId is not found - so empty result I get a crash in the code(Bad Exec/ Access) where I call the method - not in the method itself. (I'm not surprised by this but i'm not sure how to handle it)
I can't use if let on the method .. .it's not an optional. Should I be returning an empty object and check for It when the fetch result is empty?
Thanks for any help.
I would declare the function to return an optional and return nil when nothing is found
func returnStationType(stationTypeId: String) -> PersistantStationType? {
let context = container.viewContext
let request: NSFetchRequest<PersistantStationType> = PersistantStationType.fetchRequest()
request.predicate = NSPredicate(format: "%K == %#", #keyPath(PersistantStationType.stationId), stationTypeId)
do {
let result = try context.fetch(request)
if result.count != 0 {
return result[0]
} else {
print("4 Fetch result was empty for specified stationid: \(String(describing: stationTypeId))")
return nil
}
} catch {
print("Fetch on goal id: \(String(describing: stationTypeId)) failed. \(error)")
return nil
}
}
If on the error hand it is considered an error if more than one objects (or none) exists for an id then it would be better to throw an error in those situations
func returnStationType(stationTypeId: String) throws -> PersistantStationType {
let context = container.viewContext
let request: NSFetchRequest<PersistantStationType> = PersistantStationType.fetchRequest()
request.predicate = NSPredicate(format: "%K == %#", #keyPath(PersistantStationType.stationId), stationTypeId)
do {
let result = try context.fetch(request)
switch result.count {
case 0:
throw FetchError("No station type found for id \(stationTypeId)")
case 1:
return result[0]
default:
throw FetchError("Multiple station types found for id \(stationTypeId)")
}
} catch let error as NSError {
throw FetchError(error.localizedDescription)
}
}
struct FetchError: LocalizedError {
private let message: String
var errorDescription: String? {
message
}
init(_ message: String) {
self.message = message
}
}

how to modify my Core Data attributes of an entity but on all the elements of my database

hello community I am a novice and this is my first question.
how to change all the attributes of an entity and be able to change all my Core Data elements,
because I can only change the first attribute of an entity but not all my data records.
Here in this function I can only change the name
and then I get this following error has the line:
let objectUpdate = test[0] : Thread 1: Fatal error: Index out of range
func updateData() {
var newName = ""
var newPrenom = ""
newName = name.text!
newPrenom = prenom.text!
let managedContext = AppDelegate.viewContext
let fetchRequest : NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "Person")
fetchRequest.predicate = NSPredicate(format: "name = %#", newName)
do {
fetchRequest.predicate = NSPredicate(format: "prenom = %#", newPrenom)
let test = try! managedContext.fetch(fetchRequest) as! [NSManagedObject]
let objectUpdate = test[0]
objectUpdate.setValue(newName,forKey: "name")
objectUpdate.setValue(newPrenom, forKey: "prenom")
do {
try managedContext.save()
}
catch {
print(error)
}
} catch {
print(error)
}
}
There are a number of ways we can avoid this error.
Unwrapping optional .first value
Swift's Collection gives us safe way to get first item, simply by accessing the first property on a given collection. It will return an Optional<Element> value so we need to unwrap it first either by using if let of guard let
if let object = test.first {
// do something with object
}
or
guard let object = test.first else { return }
// do something with object
Checking if value at index exists
It's often a good idea to check for a specific index within the indices property before accessing the value behind it.
if test.indices.contains(0) {
let object = test[0]
// do something with object
}
These hints should prevent your code from crashing again.
Other Suggestions
This is not really safe or clean:
var newName = ""
var newPrenom = ""
newName = name.text!
newPrenom = prenom.text!
We can make it much cleaner and most importantly safer by using a guard statement
guard let newName = name.text, let newPrenom = prenom.text else { return }
Two important things happened here:
No more force-unwrapping the optional values of text [which could cause a crash]
The properties are now immutable, meaning we can be sure that what we are saving to the CoreDate is what was retreived at the beginning of the function
Since the line:
let test = try! managedContext.fetch(fetchRequest) as! [NSManagedObject]
is already wrapped in the do-catch clause, you can safely remove forced try! and replace it with try.
let test = try managedContext.fetch(fetchRequest) as! [NSManagedObject]
Let's use types! On this line you create a NSFetchRequest object for some entity named "Person".
let fetchRequest : NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "Person")
I am guessing CoreData have generated for you a NSManagedObject subclass, named Person. If this is true, you could rewrite it like this:
let fetchRequest = NSFetchRequest<Person>(entityName: "Person")
With the previous tip implemented, we can now get rid of as! [NSManagedObject] from this line:
let test = try managedContext.fetch(fetchRequest) as! [NSManagedObject]
Since the NSFetchRequest object is now nicely typed, we can take advantage of it by rewriting it like this:
let test: [Person] = try managedContext.fetch(fetchRequest)
So we are using proper types now? cool! Lets now improve this:
objectUpdate.setValue(newName,forKey: "name")
objectUpdate.setValue(newPrenom, forKey: "prenom")
by rewriting this and using properties on Person object
objectUpdate.name = newName
objectUpdate.prenom = newPrenom
No need for introducing second level of do-catch clause, since we are already in one!
do {
try managedContext.save()
}
catch {
print(error)
}
you can easily replace it with just the save() call, like this:
try managedContext.save()
Are you sure these predicates are what you want?
fetchRequest.predicate = NSPredicate(format: "name = %#", newName)
fetchRequest.predicate = NSPredicate(format: "prenom = %#", newPrenom)
What I can read from them is that you are fetching Person object where the name is newName and prenom is newPrenom and then you update it with the same exact values? Are you using some kind of identification of users? like id: Int or id: UUID? It would make much more sense to write something like this
let id: Int = // ID of the user you are currently editing
fetchRequest.predicate = NSPredicate(format: "id == \(id)")
if you are not using any id's, you could try storing the initial values of name and prenom
// in cell declaration - set when you configure your cell
var initialName: String?
var initialPrenom: String?
// then in your function:
fetchRequest.predicate = NSPredicate(format: "name = %#", initialName)
fetchRequest.predicate = NSPredicate(format: "prenom = %#", initialPrenom)
But I just noticed you also override you first predicate with the second one. You need to use NSCompoundPredicate
fetchRequest.predicate = NSCompoundPredicate(
type: .and, subpredicates: [
NSPredicate(format: "name = %#", initialName),
NSPredicate(format: "prenom = %#", initialPrenom)
]
)
Suggested version
func updateData() {
guard let newName = name.text, let newPrenom = prenom.text else { return }
let managedContext = AppDelegate.viewContext
let fetchRequest = NSFetchRequest<Person>(entityName: "Person")
fetchRequest.predicate = NSCompoundPredicate(
type: .and, subpredicates: [
NSPredicate(format: "name = %#", initialName),
NSPredicate(format: "prenom = %#", initialPrenom)
]
)
do {
let objects: [Person] = try managedContext.fetch(fetchRequest)
guard let object = objects.first else { return }
object.name = newName
object.prenom = newPrenom
try managedContext.save()
} catch {
print(error)
}
}
If the index 0 is out of range, it means that the array is empty. Before accessing it, add
if test.isEmpty{
return //the fetch request didn't return any values
}

Coredata NSpredicate predicate date in swift

A old classic question but I got.
func callThisDay(startDate:Date, endDate:Date) -> [Login]{
var datas = [Login]()
let fetchRequest:NSFetchRequest<Login> = Login.fetchRequest()
let predicate = NSPredicate(format: "date >= %# AND date < %#", argumentArray: [startDate, endDate])
fetchRequest.predicate = predicate
do{
let allData = try viewContext.fetch(Login.fetchRequest())
for data in allData{
datas.append(data as! Login)
}
}catch{
print(error)
}
return datas
}
And it always return all data. How can I just got a day?
Of course it always returns all data because you are ignoring the custom fetch request.
Replace
let allData = try viewContext.fetch(Login.fetchRequest())
with
let allData = try viewContext.fetch(fetchRequest)
The method can be simplified
func callThisDay(startDate:Date, endDate:Date) -> [Login] {
let fetchRequest : NSFetchRequest<Login> = Login.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "date >= %# AND date < %#", startDate as NSDate, endDate as NSDate)
do {
return try viewContext.fetch(fetchRequest)
} catch {
print(error)
return []
}
}

Edit all records by ID (Swift 4, CoreData)

I have Int array with values
Example:
var SelectedCard = [Int] ()
[3, 1, 2]
Me need edit my all records by order
Im tried this but app crash
for item in 0...SelectedCard.count-1 {
let order = SelectedCard[item]
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Card")
fetchRequest.predicate = NSPredicate(format: "order == %#", order)
do {
if let fetchResults = try managedContext.fetch(fetchRequest) as? [Card] {
if fetchResults.count != 0 {
for index in 0...fetchResults.count-1 {
let managedObject = fetchResults[index]
managedObject.setValue("", forKey: "folderID")
}
appDelegate.saveContext()
}
}
} catch {
print(error)
}
}
self.tableView.reloadData()
Try changing the predicate to
NSPredicate(format: "order == \(order)")

core data fetch with filter

I'm trying to add a filter (boolean value) to a fetch in core data, but I'm not sure how.
The entity name is Vinyl and the attribute that I want to use to filter is called wishlist (true or false)
if let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext {
if let vinyls = try? context.fetch(Vinyl.fetchRequest()) {
if let theVinyls = vinyls as? [Vinyl] {
self.allVinyls = theVinyls
totalVinyls = theVinyls.count
}
}
}
How can I filter for wishlist == true ?
Add an appropriate predicate.
All if lets are not necessary, the viewContext is supposed to be non-optional.
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let request : NSFetchRequest<Vinyl> = Vinyl.fetchRequest()
let predicate = NSPredicate(format: "wishlist == TRUE")
request.predicate = predicate
do {
self.allVinyls = try context.fetch(request)
totalVinyls = self.allVinyls.count
} catch { print(error) }