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

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

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

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

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.

Cryptic Core Data NSInvalidArgumentException Reason: 'Invalid relationship'

I'm trying to update a relationship in Core Data but am experiencing this issue. I have 2 entities: Trip and GPSLocation. A Trip can have many GPSLocation but a GPSLocation can only be in one Trip, hence an one-to-many relationship from Trip to GPSLocation. I set up my entities in Xcode's model editor like so:
Entity: GPSLocation relationship: trip destination: Trip inverse: gps Type: To one
Entity: Trip relationship: gps destination: GPSLocations inverse: trip Type: To many
Assuming the variable trip is an instance of my Trip entity. In my update routine, I have:
let request = NSBatchUpdateRequest(entityName: "GPSLocations")
request.predicate = somePredicate
request.propertiesToUpdate = ["trip": trip]
request.resultType = .UpdatedObjectIDsResultType
do {
let responses = try managedContext.executeRequest(request) as! NSBatchUpdateResult
print responses.result!
} catch let error as NSError {
print(error)
}
This code is giving me an NSInvalidArgumentException Reason: 'Invalid relationship' and I'm not sure why. Any help would be very appreciated! Thank you.
EDIT: My predicate is a pretty simple one: NSPredicate(format: "SELF = %#", "1"). I confirmed that record with pk 1 exists via a database visualizer.
EDIT 2:
So I did some further testing and noticed something interesting about the 2 routines that I wrote for creating and updating records in entities. Unlike with the update routine, I don't get this invalid relationship problem when I use the create routine. Here is my code for both routines:
// MARK - this routine works fine
func createRecord(entityName: String, fromKeyValue: [String:AnyObject]) -> AnyObject {
let entityDesc = NSEntityDescription.entityForName(entityName, inManagedObjectContext: managedContext)
do {
let entityType = NSClassFromString("myapp." + entityName) as! NSManagedObject.Type
let entity = entityType.init(entity: entityDesc!, insertIntoManagedObjectContext: managedContext)
for key in fromKeyValue.keys {
entity.setValue(fromKeyValue[key], forKey: key)
}
try managedContext.save()
return entity
} catch let error as NSError {
return error
}
}
// MARK - this one gives me problem..
func updateRecords(entityName: String, predicate: NSPredicate, keyValue: [String:AnyObject]) -> AnyObject {
let request = NSBatchUpdateRequest(entityName: entityName)
request.predicate = predicate
request.propertiesToUpdate = keyValue
request.resultType = .UpdatedObjectIDsResultType
do {
let responses = try managedContext.executeRequest(request) as! NSBatchUpdateResult
return responses.result!
} catch let error as NSError {
return error
}
}

Search data in DB with CoreData and swift

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.

Resources