Check object with CoreData predicate - swift

I use Core Data to find CatalogItem with predicate "parentId == 3". And I want to check in this predicate also if is exist item with CatalogItem.parentId == id". This "id" is from result item of first query part. Is it possible to use id, which i don't know yet?

I hesitate to provide this answer, because (as #JoakimDanielson says in comments) a better solution is to implement a reflexive relationship from CatalogItem to itself. However, if that's not an option, I think the following variation on this answer to a similar question should achieve what you need:
let parentFetch = CatalogItem.fetchRequest()
parentFetch.predicate = NSPredicate(format:"parentId == 3")
parentFetch.propertiesToFetch = ["id"]
let ctxtExp = NSExpression(forConstantValue: managedObjectContext)
let fetchExp = NSExpression(forConstantValue: parentFetch)
let fre = NSFetchRequestExpression.expression(forFetch: fetchExp, context: ctxtExp, countOnly: false)
let childFetch = CatalogItem.fetchRequest()
childFetch.predicate = NSPredicate(format:"parentId IN %#",fre)
... proceed to execute the fetch against the relevant context

Related

Fetch Request Predicate to filter a Core Data entity where a small NSSet is contained within larger NSSet

I'm writing a 100% SwiftUI app with iOS and macOS targets, using Core Data and NSPersistentCloudKitContainer to backup to iCloud and sync between devices signed into the same AppleID.
The three entities involved are: Meals, Portions, Foods
Each Meal has:
a many-to-many relationship with Portions
a many-to-many relationship with Foods
Each Portion has:
a many-to-many relationship with Foods
I'm attempting to prepare a predicate to filter meals where each meal portion contains a certain food OR the meal contains a certain food directly.
So I'll provide a practical example...
Meal 1
consists of...
Portions
Banana Smoothie
Egg Sandwich
Foods
Apple
The Portion with the name Banana Smoothie contains the following Foods:
Banana
Cows Milk
Honey
Meal 2
consists of...
Portions
Blueberry Smoothie
Ham Sandwich
Foods
Banana
For the macOS target, I'm using the relatively new Table structure to present a table that lists all Meal entities for a certain Food entity, including those Meal entities where one or more of the Portion entities contains that certain Food entity.
If I refer back to the above example, for the Food entity named "Banana", I'd want my predicate to filter my FetchRequest such that Meal entities with names "Meal 1" & "Meal 2" are in the results.
#FetchRequest var meals: FetchedResults<Meal>
Here is the current predicate for this FetchRequest...
let portions = NSSet(object: food.foodPortions as Any)
let predicatePartA = NSPredicate(format: "%# IN mealFoods", food)
let predicatePartB = NSPredicate(format: "ANY %# IN mealsPortions", portions)
let predicate = NSCompoundPredicate(orPredicateWithSubpredicates: [predicatePartA, predicatePartB])
where food is #ObservedObject var food: Food
and mealFoods and mealsPortions are NSSet many-to-many relationships to from every Meal object.
predicatePartA works fine, I suspect because it is one single Object IN an NSSet of objects.
predicatePartB doesn't crash, but it also doesn't resolve any meals, I suspect because I'm providing a set instead of a single object.
I've attempted to research for some time now how this might be achieved and the best I can come up with are the operators...
#distinctUnionOfSets
#"SUBQUERY()
...but apart from this website there is little documentation I can find on how to implement them.
UPDATE
With help from #JoakimDanielson I've attempted to use SUBQUERY...
let predicatePartB = NSPredicate(format: "SUBQUERY(mealsPortions, $portion, $portion IN %#).#count > 0", portions)
AND
let predicatePartB = NSPredicate(format: "SUBQUERY(mealsPortions, $portion, $portion IN %#).#count != 0", portions)
Again this does not crash, but it does not provide the expected results for the fetch request.
Any suggestions please?
Also worth noting that I've found some better documentation by Apple that supports this syntax although, because the predicate isn't working, I still not sure it is correct.
init(forSubquery:usingIteratorVariable:predicate:)
with the syntax
SUBQUERY(collection_expression, variable_expression, predicate);
Short answer...
let portions = food.foodPortions
let predicatePartB = NSPredicate(format: "(SUBQUERY(mealsPortions, $p, $p IN %#).#count != 0)", portions!)
OR, if I prepare a computed property for portions...
var portions: NSSet {
if let p = food.foodPortions { return p }
return NSSet()
}
then in the creation of the predicate I'm not required to force unwrap the optional NSSet...
let predicatePartB = NSPredicate(format: "(SUBQUERY(mealsPortions, $p, $p IN %#).#count != 0)", portions)
Most people reading this probably won't want to know the detail but nonetheless I feel compelled to write this down, so the long answer is...
... in two parts, or at least recognises two contributors who helped me solve it.
Part 1
Primarily #JoakimDanielson for confirming that SUBQUERY was the right path to a solution and for taking the time to work out the syntax for my case and also for questioning what eventually turned out to be a very basic error, the problem was not my SUBQUERY syntax but in fact the manner in which I was preparing the NSSet that I used in the predicate string.
All I needed to do was change...
let portions = NSSet(object: food.foodPortions as Any)
to...
let portions = food.foodPortions
after which I could either force unwrap it in the creation of the predicate, or otherwise prepare a computed property (the solution I chose) - as detailed above in the short answer.
This was simply an error as a result of my inadequate understanding of the collections NSSet and Set. A refresher of the swift.org docs helped me.
Part 2
Secondly this SO Q&A "How to create a CoreData SUBQUERY with BETWEEN clause?" and the reference to this clever article titled "SUBQUERY Is Not That Scary" by #MaciekCzarnik.
I went through the process of reducing the necessary iteration until I could line for line compare the SUBQUERY syntax. While it didn't actually solve my problem, this did encourage me to try numerous predicate syntax alternatives until I returned with an understanding of SUBQUERY and was able to confirm the original syntax was correct. It provided me with the type of example my brain can comprehend and work through to develop an understanding of how SUBQUERY actually works.
Because you have nothing better to read at the current moment in time...
var iterationOne: [Meal] {
let meals: [Meal] = []//all meals
var results = [Meal]()
for meal in meals {
var portionsMatchingQuery = Set<Portion>()
if let mealPortionsToCheck = meal.mealsPortions {
for case let portion as Portion in mealPortionsToCheck {
if portions.contains(portion) == true {
portionsMatchingQuery.insert(portion)
}
}
if portionsMatchingQuery.count > 0 { results.append(meal) }
}
}
return results
}
can be simplified to _
var iterationTwo: [Meal] {
let meals: [Meal] = []//all meals
let results = meals.filter { meal in
var portionsMatchingQuery = Set<Portion>()
if let mealPortionsToCheck = meal.mealsPortions {
for case let portion as Portion in mealPortionsToCheck {
if portions.contains(portion) == true {
portionsMatchingQuery.insert(portion)
}
}
return portionsMatchingQuery.count > 0
}
return false
}
return results
}
can be simplified to _
var iterationThree: [Meal] {
let meals: [Meal] = []//all meals
let results = meals.filter { meal in
let portionsMatchingQuery = meal.mealsPortions?.filter { portion in
for case let portion as Portion in meal.mealsPortions! {
return portions.contains(portion) == true
}
return false
}
return portionsMatchingQuery?.count ?? 0 > 0
}
return results
}
can be simplified to _
var iterationFour: [Meal] {
let meals: [Meal] = []//all meals
let results = meals.filter { meal in
meal.mealsPortions?.filter { portion in
for case let portion as Portion in meal.mealsPortions {
return portions.contains(portion) == true
}
return false
}.count ?? 0 > 0
}
return results
}
iterationFour == predicatePartB

How to pass and get multiple URLQueryItems in Swift?

Ok, I am working in an iMessage app and am trying to parse more than 1 url query item from the selected message here- I have been successful getting/sending just 1 value in a query:
override func willBecomeActive(with conversation: MSConversation) {
// Called when the extension is about to move from the inactive to active state.
// This will happen when the extension is about to present UI.
if(conversation.selectedMessage?.url != nil) //trying to catch error
{
let components = URLComponents(string: (conversation.selectedMessage?.url?.query?.description)!)
//let val = conversation.selectedMessage?.url?.query?.description
if let queryItems = components?.queryItems {
// process the query items here...
let param1 = queryItems.filter({$0.name == "theirScore"}).first
print("***************=> GOT IT ",param1?.value)
}
}
When I just have 1 value, just by printing conversation.selectedMessage?.url?.query?.description I get an optional with that 1 value, which is good. But with multiple I cant find a clean way to get specific values by key.
What is the correct way to parse a URLQueryItem for given keys for iMessage?
When you do conversation.selectedMessage?.url?.query?.description it simply prints out the contents of the query. If you have multiple items then it would appear something like:
item=Item1&part=Part1&story=Story1
You can parse that one manually by splitting the string on "&" and then splitting the contents of the resulting array on "=" to get the individual key value pairs in to a dictionary. Then, you can directly refer to each value by key to get the specific values, something like this:
var dic = [String:String]()
if let txt = url?.query {
let arr = txt.components(separatedBy:"&")
for item in arr {
let arr2 = item.components(separatedBy:"=")
let key = arr2[0]
let val = arr2[1]
dic[key] = val
}
}
print(dic)
The above gives you an easy way to access the values by key. However, that is a bit more verbose. The way you provided in your code, using a filter on the queryItems array, is the more compact solution :) So you already have the easier/compact solution, but if this approach makes better sense to you personally, you can always go this route ...
Also, if the issue is that you have to write the same filtering code multiple times to get a value from the queryItems array, then you can always have a helper method which takes two parameters, the queryItems array and a String parameter (the key) and returns an optional String value (the value matching the key) along the following lines:
func valueFrom(queryItems:[URLQueryItem], key:String) -> String? {
return queryItems.filter({$0.name == key}).first?.value
}
Then your above code would look like:
if let queryItems = components?.queryItems {
// process the query items here...
let param1 = valueFrom(queryItems:queryItems, key:"item")
print("***************=> GOT IT ", param1)
}
You can use iMessageDataKit library. It makes setting and getting data really easy and straightforward like:
let message: MSMessage = MSMessage()
message.md.set(value: 7, forKey: "user_id")
message.md.set(value: "john", forKey: "username")
message.md.set(values: ["joy", "smile"], forKey: "tags")
print(message.md.integer(forKey: "user_id")!)
print(message.md.string(forKey: "username")!)
print(message.md.values(forKey: "tags")!)
(Disclaimer: I'm the author of iMessageDataKit)

Core data fetch request not working

I have ShopItem and Product tables. Product has relation to ShopItem. I want to get all products from ShopItem object. I have created a method at ShopItem class
class ShopItem: NSManagedObject {
func fetchProducts(q: String) {
// some code ...
let fetchRequest = NSFetchRequest(entityName: "Product")
fetchRequest.predicate = NSPredicate(
format: "shopitem == %# AND keyword == %#",
self.objectID, String(jsonObj["keyword"])
)
fetchRequest.fetchLimit = 1;
do {
fetchResults = try self.managedObjectContext!.executeFetchRequest(fetchRequest) as! [Product]
} catch {
fatalError("Fetching from the store failed")
}
}
}
At logs it generates me the following sql:
SELECT 0, t0.Z_PK, t0.Z_OPT, t0.ZPRODUCT_TITLE, t0.ZPRODUCT_URL,
t0.ZSHOPITEM FROM ZPRODUCT t0 WHERE ( t0.ZSHOPITEM = ? AND
t0.ZKEYWORD = ?) LIMIT 1
And results is always empty.
If you have a relationship, why the fetch request? If everything is set up correctly, you just filter your products by keyword.
// filter by kw
let filteredProducts = shopItem.products.filter { $0.keyword == kw }
Your fetch request looks correct (although you don't need to pass self.objectID in your predicate, self is sufficient). When I see mysteriously empty relationships it's typically one of two things:
You aren't setting the relationship at creation like you think you are (or whatever even relates the two entities).
You are setting the relationship, but you have a to-one relationship configured in your data model instead of a to-many, which means only the last relationship you create will be present.
jsonObj["keyword"] returns an optional.
The String representation will look like Optional("keywordValue")
Unwrap the optional or use optional bindings if the value can be nil.

Searchbar with core data issues

I have a search bar.And data displayed in labels with scrollview.
For ex:
core data Fields :
1.id
2.company
3.Employe Name
4.Address
If i type id,company or Employee Name in searchbar i want to dispaly associated results.
my code :
For search data :
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
var request = NSFetchRequest(entityName: "Agency")
request.returnsObjectsAsFaults = false
var countResult : NSArray = context.executeFetchRequest(request, error: nil)!
let result = NSPredicate(format: "SELF CONTAINS[c] %#",searchText)
self.filtered = self.countResult.filteredArrayUsingPredicate(result!)
if (filtered.count == 0 ) {
searchActive = false;
}else {
searchActive = true;
}
println(filtered)
}
It shows an error " 'Can't use in/contains operator with collection".
These codes cannot satisfy what i want.And also i dont have a idea how to fetch the related rows according to enter value in search bar.
Thanks in Advance.
The first problem is your predicate - you're trying to use CONTAINS on an NSManagedObject subclass, but CONTAINS only works with String. To check whether your search text is contained within any of your managed objects you need to evaluate whether it is contained in each attribute (in your case id, company and empolyeeName, I'm assuming they're all Strings).
To do this you should change your predicate to:
let searchPredicate = NSPredicate(format: "id BEGINSWITH %# OR
company BEGINSWITH %# OR
employeeName BEGINSWITH %#",
searchText, searchText, searchText)
I would recommend using BEGINSWITH instead of CONTAINS[c] since when searching your user is likely to be entering the first part of the phrase. Also, as Apple said in their 2013 WWDC talk Core Data Performance Optimization and Debugging -
...we've got begins with and ends with and that's by far the cheapest query that you can execute.
...
Contains is more expensive because we have to work along and see
whether it contains...
And in the case of a search, you want it to be fast!
Secondly, you don't need to filter your results after getting them back from CoreData. You can set the predicate property on your NSFetchRequest and your returned results will be filtered. For example:
let request = NSFetchRequest(entityName: "Agency")
request.predicate = // Your predicate...
let results = context.executeFetchRequest(request, error)
// Now do what you need with the results.
A final note, it's best not to force unwrap your results from executeRequest in case there is some problem and nil is returned - in that case your app would crash. You could instead use:
if let unwrappedResults = results {
// Now do what you want with the unwrapped results.
}
I suspect it has something to do with your use of SELF in the predicate format, and the "collection" referred to in the error message is the controller sub/class within which your code resides.
Try something like this (forgive me I'm Obj-C not Swift so may have the syntax incorrect).
let searchAttribute = <<entity.attribute key path>>
let result = NSPredicate(format:"%K CONTAINS[cd] %#",searchAttribute, searchText)
Where %K refers to the key path, that in the case of Core Data is your entity attribute. For example: Agency.name if that attribute exists for your Agency object.
Read about Predicate Format String Syntax.
UPDATE after third comment...
In my apps my solution includes the creation of a custom method in an extension of the Core Data generated NSManagedObject subclass. If that sounds like you know what I mean, let me know and I will post details.
In the meantime, create a custom method in whatever class your UISearchBar is controlled... (apologies Obj-C not Swift)
- (NSString *)searchKey {
NSString *tempSearchKey = nil;
NSString *searchAtrribute1 = Agency.attribute1;
NSString *searchAtrribute2 = Agency.attribute2;
NSString *searchAtrribute3 = Agency.attribute3;
NSString *searchAtrribute4 = Agency.attribute4;
tempSearchKey = [NSString stringWithFormat:#"%# %# %# %#", searchAtrribute1, searchAtrribute2, searchAtrribute3, searchAtrribute4];
return tempSearchKey;
}
You'll obviously need a strong reference for your Agency entity object to persist within the class, otherwise you will need to embed this bit of code into your searchBar function.
Work OK?

NSPredicate with Swift and Core Data

i have a Core Data Object and i have 2 Fieds (one String(GUID) and one Int which i want to use as Filter)
So in SQL it would be "SELECT * FROM Answers WHERE qIndex = 1 AND GUID = '88bfd206-82fb-4dd0-b65d-096f8902855c'
Ive tried it with Core Data but i am not able to Filter with the String Value.
Here is my Code
var request = NSFetchRequest(entityName: "Answers")
request.returnsObjectsAsFaults = false;
let resultPredicate1 = NSPredicate(format: "qIndex = %i", qIndex)
let resultPredicate2 = NSPredicate(format: "formUUID = %s", formUUID)
var compound = NSCompoundPredicate.andPredicateWithSubpredicates([resultPredicate1, resultPredicate2])
request.predicate = compound
var results:NSArray = context.executeFetchRequest(request, error: nil)
Any ideas what i am doing Wrong? With the Same Code and Filter for 2 Integer Values it works fine.
Thanks in Advance
If formUUID is an NSString or a Swift String then you have to use the
%# placeholder:
let resultPredicate2 = NSPredicate(format: "formUUID = %#", formUUID)
This is not the exact response to your question, but a problem people might now encouter with your code now:
In the latest version of XCode, you must now unwrap the predicate, like this:
var compound = NSCompoundPredicate.andPredicateWithSubpredicates([predicate1!, predicate2!])
because NSPredicate initializer now return NSPredicate? type.
Instead of worrying about %# conversions and then composing AND predicates, you can use the PredicatePal framework:
let compound = *(Key("qIndex") == qIndex && Key("formUUID") == formUUID)
Assuming that qIndex and formUUID are the correct type, Swift will automatically deduce the correct types for the Key objects.