Search data in DB with CoreData and swift - ios

I'm a new in swift and CoreData and I have a problem:
I have DB with 2 columns: "name" and "number", for example
name number
Bob 2
Helena 5
Helga 1
Matilda 0
I connect my UITableViewController with DB across CoreData and it's working (i see all DB in my simulator of iphone)
I want find with swift in my DB cells of column "number" with value, for example, "1" and "2" and show proper cell from column "name" and as result I want to see:
Bob 2
Helga 1
How better to do it? I tried to work with NSPredicate, but I don't understand how it works and how to do so that it will be worked.
Thanks!

Hi Add below function in your NSManagedObject extension
1) fetch data from coredata by id using predict
class func Search(PredictName:String, Uid:String, entityDescription: String,managedObjectContext: NSManagedObjectContext = appDelegate.managedObjectContext) -> [AnyObject]?
{
var ar:[AnyObject] = []
do
{
let predicate = NSPredicate(format: "\(PredictName) == %#", Uid)
let request = NSFetchRequest(entityName: entityDescription)
request.predicate = predicate
let result = try managedObjectContext.executeFetchRequest(request)
ar = result
}
catch(_)
{
ar = []
}
return ar as [AnyObject]
}
Function Call :
var lists:[ModelClassName]? = AdvertisementDataList.findByTypeInContext("user_id", url: self.Uid, entityDescription: "CoredataEntityName") as? [AdvertisementDataList]
It will return you predict column name data by row id
2) fetch all the data from coredata
class func Search(PredictName:String, entityDescription: String,managedObjectContext: NSManagedObjectContext = appDelegate.managedObjectContext) -> [AnyObject]?
{
var ar:[AnyObject] = []
do
{
let predicate = NSPredicate(format: "\(PredictName)")
let request = NSFetchRequest(entityName: entityDescription)
request.predicate = predicate
let result = try managedObjectContext.executeFetchRequest(request)
ar = result
}
catch(_)
{
ar = []
}
return ar as [AnyObject]
}
Function Call :
var lists:[ModelClassName]? = AdvertisementDataList.findByTypeInContext("user_id", entityDescription: "CoredataEntityName") as? [AdvertisementDataList]
It will return all the data by predict name.

Related

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

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>()

Querying Core data with predicates

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.

How to make simple join in relationship of Core Data Swift

I have Core Data with relationship:
extension Rating {
#NSManaged var date: NSString?
#NSManaged var rating: NSNumber?
#NSManaged var ratenames: RateNames?
}
extension RateNames {
#NSManaged var name: String?
#NSManaged var rating: NSSet?
}
And I need to select all values from RateNames with all data from Rating linked to RateNames from a selected date.
For example RateNames data:
name=a; name=b;
For example RateNames data:
date=10-02-2016; rating=5; linked to a
date=10-02-2016; rating=3; linked to b
date=09-02-2016; rating=2; linked to a
date=08-02-2016; rating=3; linked to a
date=08-02-2016; rating=1; linked to b
For example I need result for 08-02-2016
Result should be:
{(name:a, date:08-02-2016, rating=3), (name:b, date:08-02-2016, rating=1)}
result for 09-02-2016 date should be the following:
{(name:a, date:09-02-2016, rating=2), (name:b, date:nil, rating=nil)}
I also do need b in results because I need to see whether it is null or not.
I am trying to do something like:
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "RateNames")
do {
let results = try managedContext.executeFetchRequest(fetchRequest)
for result in results {
let child = result. ..some var here.. as! Rating
But cannot get how to implement this
It's easier to get what you want by fetching the Rating objects, and using the relationship to get the name of the related RateName objects:
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Rating")
do {
let results = try managedContext.executeFetchRequest(fetchRequest) as! [Rating]
for result in results {
let name = result.ratenames.name
let date = result.date
let rating = result.rating
print("name:\(name), date:\(date), rating:\(rating)")
}
}
This will print results similar to your expected results, though it won't include the (name:b, date:nil, rating=nil).
Update
If you want to limit the above to a given date, you can use a predicate for the fetch request:
fetchRequest.predicate = NSPredicate(format:"date == %#", chosenDate)
But since you want to include, (name:b, date:nil, rating=nil), you will need to fetch ALL the RatingName objects. The rating property of each object will include any and all Ratings to which it is related. So I think you will then need to filter them to identify any for the correct date:
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "RateNames")
do {
let results = try managedContext.executeFetchRequest(fetchRequest)
let datePredicate = NSPredicate(format:"date == %#", chosenDate)
for result in results {
let filteredRatings = result.rating.filteredSetUsingPredicate(datePredicate)
if filteredRatings.count > 0 {
let rating = filteredRatings.anyObject()
print("name:\(result.name), date:\(rating.date), rating:\(rating.rating)")
} else {
print("name:\(result.name), date:nil, rating:nil")
}
}
}
This assumes there can be only one Rating for each RatingName for a given date; if not you will have to iterate through the filteredRatings set.
you need to just setup relationship in Datamodel like i have created for following example
From your code i found that you didn't mentioned One-to-Many Relationship .
Then create again sub class of NSManageObject. xCode will create all needed variables for same.

Swift - Core Data return all rows for attribute

I'd like to return all rows for a given attribute stored in my core data entity. I know how to retrieve rows based on a filtered predicate, but I would like to be able to return all of the rows without specifying a value for the predicate. The code I'm currently using is as follows:
func getUsername() -> NSString {
var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!
var request = NSFetchRequest(entityName: "User")
//request.returnsObjectsAsFaults = false
//request.predicate = NSPredicate(format: "fstrUsername = %#", pstrUsername)
var results:NSArray = context.executeFetchRequest(request, error: nil)!
if results.count > 0 {
var res = results[0] as NSManagedObject
return res.valueForKey("fstrUsername") as NSString
}
else {
return "false"
}
}
Can anyone tell me how to return all rows for an attribute without having to specify a full or partial value to match on in the predicate? Thanks in advance.
Just remove the predicate code and you will retrieve all the rows!

Resources