Querying Core data with predicates - ios

So i am building this app using CoreData.
The two entities I have are Lists and Items. They have a to many relationship i.e. A List can have multiple items.
For example: List1 has Items: item1, item2
I have written the code for storing the Items in the specific list but i am having a difficult time on figuring out how to fetch and proccess the Items from a specific List.
What I have done so far is as follows
func getItemsOnList(){
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
//fetchRequest to get the List
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "List")
let predicate = NSPredicate(format: "title == %#", listName)
fetchRequest.returnsObjectsAsFaults = false
fetchRequest.predicate = predicate
if let fetchResults = try? context.fetch(fetchRequest){
if fetchResults.count > 0 {
for listEntity in fetchResults {
let list = listEntity as! List
print(list.title as Any)
itemsOnList = list.contains!
print(itemsOnList)
print("The list with name:\(list.title)has \(itemsOnList.count) items")
}
}
}
}
This function returns an NSSet which is suppose to contain all the Items in that particular List.
My Data model is :
My questions are:
A. Is the way I coded the getItemsOnList() function correct? Or is there something I am doing wrong.
B. Given that the code is correct and the NSSet I get is correct with all the Items, how would I get each Item in that NSSet in order for me to put it on a TableView.

func getItemsWithFilter(filterQuery:NSPredicate,sortBy:String?,order:Bool) -> Array<Items> {
var fetchedResults:Array<Items> = Array<Items>()
let fetchRequest = NSFetchRequest(entityName: "Items")
fetchRequest.predicate = filterQuery
if sortBy != nil{
let sortDescriptor = NSSortDescriptor(key:sortBy! ,
ascending:order )
let sortDescriptors = [sortDescriptor]
fetchRequest.sortDescriptors = sortDescriptors
}
//Execute Fetch request you can go with your approach to
do {
fetchedResults = try self.mainContextInstance.executeFetchRequest(fetchRequest) as! [Items]
} catch let fetchError as NSError {
print("retrieveById error: \(fetchError.localizedDescription)")
fetchedResults = Array<Items>()
}catch {
fetchedResults = Array<Items>()
}
return fetchedResults
}
for calling this method you can pass the List item in predicate to as query saying fetch Items in which List.id == XXX
let predicate = NSPredicate(format: "ANY list.name in %#", name)
let myResult = self.getItemsWithFilter(predicate,sortBy:nil,order:false)

Answers:
A) Yes. You are using the graph of objects from a fetch. That is the main functionality of Core Data.
B) To fill a table view you cannot use a set. You need some kind of sorted list of elements. That is, an array. Use -orderedArrayUsingDescriptors: to get the sorted array.

Related

Swift - Get one-to-many relationship

let's imagine that we have 2 entities:
-People (name, age, ..)
-House (color)
we recorded the data several times with house.addToPeople (newPeople) for each house
we want to get all the people of the house colored blue
how do we fetch this?
I tried this code but it gets all the people
let appD = UIApplication.shared.delegate as! AppDelegate
let context = appD.persistentContainer.viewContext
let peopleFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "People")
let houseFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "House")
houseFetch.fetchLimit = 1
houseFetch.predicate = NSPredicate(format: "color = %#", "blue")
...
let res = try? context.fetch(peopleFetch)
let resultData = res as! [People]
how to do this ?
Try this function. What it does is fetching all of the People and creating an array with all of the results.
func getAllItems() -> [People]? {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "People")
request.returnsObjectsAsFaults = false
do {
let result: NSArray = try context.fetch(request) as NSArray
return (result as? [People])!
} catch let error {
print("Errore recupero informazioni dal context \n \(error)")
}
return nil
}
If you want to perform your search following certain criteria such as a color, use the following code after request:
//Here i'm searching by index, if you need guidance for your case don't hesitate asking
request.predicate = NSPredicate(format: "index = %d", currentItem.index)
Edit: actually the code above is just to get all of the people, if you want to base your search on the houses do the following:
func retrieve()-> [People]{
//Fetch all of the houses with a certain name
let houseRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "House")
houseRequest.predicate = NSPredicate(format: "name = %#", "newName") //This seearch is by name
houseRequest.returnsObjectsAsFaults = false
do {
//put the fetched items in an array
let result: NSArray = try context.fetch(houseRequest) as NSArray
let houses = result as? [Houses]
//Get the people from the previous array
let people: [People]? = (houses.people!.allObjects as! [People])
return people
} catch let error {
print("Errore recupero informazioni dal context \n \((error))")
}
return nil
}
Thank you for your answer !
In this example "houses" is an array, so we have to add an index ➔ houses[0].people!.AllObjects
And thank you very much for your explanation.

Output of fetched data to a variable as an Int

In this example, print gewicht gives an output of optional({10)} i need the output (10) as
an Int assigned to a variable . So the output has to be let mijnGewicht = 10
How can i do that. Iam new to swift, so excuse me for the question.
let appDelegate = UIApplication.shared.delegate as? AppDelegate
let managedObjectContext = appDelegate!.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Dogs")
fetchRequest.predicate = NSPredicate(format: "name = %#", "Toni")
fetchRequest.returnsObjectsAsFaults = false
fetchRequest.relationshipKeyPathsForPrefetching = ["gewicht"]
do {
let fetchedResults = try managedObjectContext.fetch(fetchRequest)
for i in fetchedResults {
dogs.append(i as! NSManagedObject)
for i in dogs {
let gewicht = i.value(forKeyPath: "gewicht.kg")
print(gewicht)
}
Dealing with unspecified NSManagedObject and value(forKeypath: is outdated.
Take advantage of the generic abilities of Core Data. The benefit is no type cast and no Any.
First declare dogs as
var dogs = [Dogs]()
By the way it's highly recommended to name entities in singular form. Semantically you have an array of Dog instances.
Create the fetch request for the specific NSManagedObject subclass Dogs
As gewicht is a to-many relationship you have to use a loop to get all values
let appDelegate = UIApplication.shared.delegate as? AppDelegate
let managedObjectContext = appDelegate!.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<Dogs>(entityName: "Dogs")
fetchRequest.predicate = NSPredicate(format: "name = %#", "Toni")
fetchRequest.returnsObjectsAsFaults = false
do {
let result = try managedObjectContext.fetch(fetchRequest)
dogs.append(contentsOf: result)
for dog in dogs {
for gewicht in dog.gewicht {
let kg = gewicht.kg
print(kg)
}
}
} catch { print(error) }
If the relationship and/or the attribute is declared optional (which is still unclear) you have to unwrap the optional.
And consider that the integer value is Int16, Int32 or Int64 (unfortunately this information is missing, too). There is no Int type in Core Data.
And it's up to you how to distinguish the many values.
Try changing your code like this, it checks if the value you are assigning is not nil and then prints it
for i in dogs {
if let mijnGewicht = i.value(forKeyPath: "gewicht.kg"){
print(mijnGewicht)
}
}
You can try something like this
let gewicht = i.value(forKeyPath: "gewicht.kg")
if let gewichtInt = gewicht as? Int {
print(gewichtInt)
}
for i in dogs {
if let gewicht = i.value(forKeyPath: "gewicht.kg") {
print(gewicht) // this will give you the safe value as Int, if the value is nill it will not come in this if condition
}
let x = i.value(forKeyPath: "gewicht.kg") ?? 0
print (x) //this will give you wrapped safe value of gewicht.kg if exists else it will give you 0
}
here in above example i have shown you two ways to safe cast a value from optional, you can also use guard or guard let on the basis of your requirement

Dynamic filtering with Swift CoreData

I am developing an application that retrieves data from CoreData. I retrieve a list of items from the database and display these on screen.
The user has an option to filter these items for up to 5 categories in 5 separate drop downs. What is the best way of doing this dynamically? What I mean by that, is if the user selects one filter option, only the items that match that filter will be shown, as well as the other filter options then only showing filter options that exist for the already filtered items.
I hope that makes sense!
This is the code I currently have for retrieving the items:
func showDropDown(filterButton: UIButton) -> Void {
selectedButton = filterButton
let popController = UIStoryboard(name: STORYBOARD_NAME,
bundle: nil).instantiateViewController(withIdentifier: STORYBOARD_ID) as! FilterDropDownViewController
popController.modalPresentationStyle = .popover
popController.delegate = self
popController.popoverPresentationController?.permittedArrowDirections = .up
popController.popoverPresentationController?.delegate = self
popController.popoverPresentationController?.sourceView = filterButton
popController.popoverPresentationController?.sourceRect = filterButton.bounds
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Item")
var predicate = NSPredicate(format: "code matches[c] '\(code!)'")
fetchRequest.returnsObjectsAsFaults = false
fetchRequest.predicate = predicate
let entity = NSEntityDescription.entity(forEntityName: "Item",
in: context)
fetchRequest.resultType = .dictionaryResultType
let entityProperties = entity?.propertiesByName
let filterToFetch = "filter\(filterButton.tag)"
let propertiesToFetch: [Any] = [entityProperties![filterToFetch]!]
fetchRequest.propertiesToFetch = propertiesToFetch
fetchRequest.returnsDistinctResults = true
var result = [[String : String]]()
do {
result = try context.fetch(fetchRequest) as! [[String : String]]
} catch {
print("Unable to fetch managed objects for Item).")
}
var filterArray = [Filter]()
for dict in result {
if let search = dict[filterToFetch] {
predicate = NSPredicate(format: "code matches[c] '\(search)'")
let filterCode = DatabaseHelper.fetchRecordsForEntity(entity: "Filter",
managedObjectContext: context,
predicate: predicate) as! [Filter]
filterArray.append(filterCode.first!)
}
}
popController.filterArray = filterArray
present(popController, animated: true, completion: nil)
}
You can do it with these simple steps:
Create a NSFetchResultsController with the appropriate predicate based on the current filter settings (use a NSCompoundPredicate), and fetch with it. Set the view controller as the delegate and reload the data of the collectionView when data changes (it seems you don't expect data to be changing while the user is viewing it, so you can just keep it simple). Don't forget to reload the collectionView when updating the NSFetchResultsController.
Now run through all the fetchedObjects in the NSFetchResultsController and see what filterable properties it has. Add those properties to a set (one for each filter category). Then look at the set to determine what filters to display and update the UI.
When the filter changes set the delegate of the current NSFetchResultsController to nil, before creating a new one and the create a new one as described in step one.
In the code you shared you are needlessly doing an complicated fetch to figure out which filters are relevant. I don't know if your code is correct or not, but I do know that it is complicated. And it is faster to just look at the properties in the managedObject that you already have access to in the fetchResultsController. Those items are already fetched and in memory - so it doesn't need to hit the database again. And filtering those item in code is easier than figuring out how to write a complex predicate.

How to “downcast” an array of [NSManageObject] to the selected entity?

I am developing an App using CoreData.
I have 5 entities (A, B, C, D, E) and 90% of the attributes of each entity are common. 10% are different.
I created an array of [NSManageObject] to store the fetchRequest of the selected entity. Until that point everything seems to work.
Here is my fetchRequest code. First of all I made an extension of NSManagedObjectContext:
extension NSManagedObjectContext {
func fetchMOs (_ entityName: String, sortBy: [NSSortDescriptor]? = nil, predicate: NSPredicate? = nil) throws -> [NSManagedObject] {
let request = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
request.returnsObjectsAsFaults = false
request.predicate = predicate
request.sortDescriptors = sortBy
return try! self.fetch(request) as! [NSManagedObject]
}
}
Then I request the data by calling to this function within the context:
documentArray = try! context.fetchMOs(requestedEntity!, sortBy: requestedSortBy, predicate: requestedPredicate)
The problem comes when I want to access the attributes of the selected entity to work with them.
For example, I selected entity A and the fetchRequest stored the data in the array [NSManageObject]. Now I want to print one attribute of the entity:
[NSManageObject].attribute1 <— but this is incorrect.
It should be: [A].attribute1
I guess I could do a switch statement to downcast and work with the data:
Switch entitySelected {
Case “A”:
arrayOfMO as! [A]
arrayOfMO.attribute1 ......
And so on for each entity. But it seems to me that there should be a more clean way of doing that.
The data stored in the entities are Strings and what I want to do with it is just to fill labels and buttons in a tableViewController.
Thanks.
Try next:
extension NSManagedObjectContext {
func fetchMOs<T: NSManagedObject>(sortBy: [NSSortDescriptor]? = nil, predicate: NSPredicate? = nil) throws -> [T] {
let request = NSFetchRequest<T>(entity: T.entity())
request.returnsObjectsAsFaults = false
request.predicate = predicate
request.sortDescriptors = sortBy
return try? self.fetch(request) ?? []
}
}
Then you can get
let results: [SomeMoClass] = moc.fetchMOs<SomeMoClass>()

Getting objects from NSSet and populating TableView

I have this piece of code as shown below
func getItemsOnList(){
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
//fetchRequest to get the List
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "List")
let predicate = NSPredicate(format: "title == %#", listName)
fetchRequest.returnsObjectsAsFaults = false
fetchRequest.predicate = predicate
if let fetchResults = try? context.fetch(fetchRequest){
if fetchResults.count > 0 {
for listEntity in fetchResults {
let list = listEntity as! List
print(list.title as Any)
itemsOnListSet = list.contains!
What this does is it gets the Items from the specified List using the .contains relationship between the two entities, and saves all the items in to an NSSet.
What i want to do is to populate a TableView with the objects that are in the NSSet.
Is there a function related to NSSet which allows me to get the items from the set? Or should i save the items in an Array instead of an NSSet.
P.S. the .contains relationship is of type NSSet
#NSManaged public var contains: NSSet?
why don't you convert the Set to Array using,
if let _ = list.contains {
let itemsOnListArray = list.contains!.allObjects
}
else
if let unwrappedList = list.contains {
let itemsOnListArray = unwrappedList.allObjects
}
Now use your itemsOnListArray as your tableView's data source :)
EDIT:
Your code
let item = itemsOnListArray[indexPath.row]
cell.textLabel?.text = item as? String
Assumes itemsOnListArray is a array of strings!!! Which is absolutely impossible because list.contains! is a set of NSManagedObjects or if you created mapped subclasses of ManagedObjects than it will contain a set of your managed objects like items.
What you should be doing is (because you have not provided the description of item am assuming item has a name property in it)
let item = itemsOnListArray[indexPath.row] as! Item
cell.textLabel?.text = item.name

Resources