Delete all data from an attribute in CoreData - ios

How to delete all data for example from an attribute <name>, not Entity, from attribute. I have an entity name - Users, attribute - name and I don't know how to delete all data from an attribute.

for delete the all data you can use this function
func deleteAllData(entity: String) {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: entity)
fetchRequest.returnsObjectsAsFaults = false
do
{
let results = try managedContext.executeFetchRequest(fetchRequest)
for managedObject in results
{
let managedObjectData:NSManagedObject = managedObject as! NSManagedObject
managedContext.deleteObject(managedObjectData)
print("Deleted")
}
} catch let error as NSError {
print(error)
}
}
and after that call the function like this
deleteAllData(entity: "your Entity name")

You have to set that attibute to nil and save the context. This is how you have to remove the attribute from entity. You can't delete it like how an entity is deleted from coreData.

I just renewed Rahuld and Piet.t code for Swift and it works.
func deleteAllData(entity: String) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let managedObjectContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: entity)
fetchRequest.returnsObjectsAsFaults = false
do
{
let results = try managedObjectContext.fetch(fetchRequest)
for managedObject in results
{
let managedObjectData:NSManagedObject = managedObject
managedObjectContext.delete(managedObjectData)
print("Deleted")
}
} catch let error as NSError {
print(error)
}
try? managedObjectContext.save()
self.fetch(entity: "ListItem")
}
and after that call the function like this
deleteAllData(entity: "your Entity name")
in addition after you need to show the result so you will fetch your data again.
the below function can be used for it
func fetch(entity: String) {
//Veritabanındaki bilginin ekrana gelmesi için veriyi çekme işlemi
let appDelegate = UIApplication.shared.delegate as? AppDelegate
let managedObjectContext = appDelegate?.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSManagedObject>.init(entityName: entity)
data = try! managedObjectContext!.fetch(fetchRequest)
tableView.reloadData()
}
use it like:
self.fetch(entity: "your entity name")
or like this:
fetch(entity: "your entity name")

Related

I want to fetch data from CoreData and if the data exist I want to return true, if not I want to return false

I want to fetch data from CoreData and if the data exist I want to return true, if not I want to return false, I'm working on Favoris, so I want to fetch if the event id exists in CoreData, if it does i want to return true and if not it will return false, there is my code:
func retrieveFavoris() {
//As we know that container is set up in the AppDelegates so we need to refer that container.
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
//We need to create a context from this container
let managedContext = appDelegate.persistentContainer.viewContext
//Prepare the request of type NSFetchRequest for the entity
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Favoris")
do {
let result = try managedContext.fetch(fetchRequest)
for data in result as! [NSManagedObject] {
print(data.value(forKey: "id_event") as! String)
}
} catch {
print("No Favoris")
}
}
PS: my xcdata file contains one Entity "Favoris" which contains only one attribute "id_event"
I want to test if id event exists in CoreData, so i think i have to pass in parameters an event_id that i enter and then test if it exist, so the function should return a boolean value true if exist and false if does not exist.
Any help please? Thank you
You have to add a parameter, a return type and a predicate for the id event.
func retrieveFavoris(idEvent: Int) -> Bool {
//As we know that container is set up in the AppDelegates so we need to refer that container.
let appDelegate = UIApplication.shared.delegate as! AppDelegate
//We need to create a context from this container
let managedContext = appDelegate.persistentContainer.viewContext
//Prepare the request of type NSFetchRequest for the entity
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Favoris")
fetchRequest.predicate = NSPredicate(format: "id_event = %ld", idEvent)
do {
return try !managedContext.fetch(fetchRequest).isEmpty
} catch {
print("No Favoris", error)
return false
}
}
If you want to check only data is exists or not then use result.count:
func retrieveFavoris() -> Bool {
//As we know that container is set up in the AppDelegates so we need to refer that container.
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
//We need to create a context from this container
let managedContext = appDelegate.persistentContainer.viewContext
//Prepare the request of type NSFetchRequest for the entity
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Favoris")
let predicate = NSPredicate(format: "id_event = %#", id_event_value)
fetchRequest.predicate = predicate
do {
let result = try managedContext.fetch(fetchRequest)
return (result.count > 0)
} catch {
print("No Favoris")
return false
}
}

Swift core data many-to-many relationship not saving entities

I use the following code to add a pokemon entity to the pokemons relationship in user where pk is an NSManagedObject of type pokemon
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext let fetchRequest = NSFetchRequest <NSManagedObject>
(entityName: "User")
let pokemonRequest = NSFetchRequest <NSManagedObject>
(entityName: "Pokemon")
let manyRelation = user.value(forKeyPath: "pokemons") as! NSMutableSet
manyRelation.add(pk)
do {
try managedContext.save()
}
catch let error as NSError {
print ("Could not save. \(error), \(error.userInfo)")
}
The application shows the user has a pokemon entity in the pokemons relationship. I move to the profile view to view your pokemons with the following code:
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let destination = storyboard.instantiateViewController(withIdentifier: "ProfileViewController") as! ProfileViewController
self.navigationController?.pushViewController(destination, animated: true)
Where I load the user data with this code:
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext let fetchRequest = NSFetchRequest <NSManagedObject>
(entityName: "User")
do {
let users = try managedContext.fetch (fetchRequest)
for user in users {
let name = user.value (forKey: "username")
as? String let pks = user.value (forKey: "pokemons")
as? NSMutableSet if name = = username {
for pokemon in pks! {
self.pokemonsList.append (pokemon as! NSManagedObject)
}
}
}
}
catch let error as NSError {
print ("Could not fetch. \(error), \(error.userInfo)")
}
However, the pks variable is always empty. Why is the variable always empty? The user variable does have pokemons filled with:
pokemons = "<relationship fault: 0x600001726da0 'pokemons'>";
A common mistake is to forget to save the managed object context after you modify it. A managed object context is just a workspace... if you don't save it, your changes never make it into the persistent store, and you won't see your changes when you later make a fetch request. So... make sure you're saving the context and any parent contexts.

Delete core data items

How can i delete all the data in a particular attribute in an entity i don't want to empty all the attributes in the entity here is what i have now which deletes all the attributes in an entity
func deletObject(){
let fetchRequest = NSFetchRequest()
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
fetchRequest.includesPropertyValues = false
let context:NSManagedObjectContext = appDel.managedObjectContext
let moc = context
fetchRequest.entity = NSEntityDescription.entityForName("Cart", inManagedObjectContext: moc)
do {
if let results = try moc.executeFetchRequest(fetchRequest) as? [NSManagedObject] {
for result in results {
moc.deleteObject(result)
}
try moc.save()
self.cart = [Cart]()
self.tableView.reloadData()
totalAmouLa.text = "₦\(Int(totalHoursWorkedSum))"
}
} catch {
print("FAILED")
}
}
EDIT
I want to delete delivery in the Cart entity
Image
You cannot delete an attribute from the Core Data model, you can only reset the value.
executeFetchRequest returns guaranteed [Cart] on success, the optional binding will never fail
func deletObject(){
let fetchRequest = NSFetchRequest()
let appDel = UIApplication.sharedApplication().delegate as! AppDelegate
let context = appDel.managedObjectContext
fetchRequest.entity = NSEntityDescription.entityForName("Cart", inManagedObjectContext: context)
do {
let results = try context.executeFetchRequest(fetchRequest) as! [Cart]
results.forEach { $0.delivery = 0.0 }
try context.save()
self.tableView.reloadData()
totalAmouLa.text = "₦\(Int(totalHoursWorkedSum))"
} catch {
print("FAILED")
}
}

fetching a custom object from core data into an array

I'm having trouble fetching my object from core data. Object looks like this:
class cilj: NSObject {
var imeCilja: String
var slikaCilja: String }
My entity is called Entity and has two Attributes "tekst" and "slika", both of type String. My save func is this:
func saveImage(goalName:String, imageName:String) {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let entityDescription = NSEntityDescription.entityForName("Entity", inManagedObjectContext:managedContext)
let thingToSaveToCD = NSManagedObject(entity: entityDescription!, insertIntoManagedObjectContext: managedContext)
thingToSaveToCD.setValue(globalGoalTitle, forKey: "tekst")
thingToSaveToCD.setValue(globalGoalImagePath, forKey: "slika")
do {
try managedContext.save()
print("managed to save to core data")
//5
// listaObjekata.append(cilj5) as! [cilj]
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
}
I use an alertController to pick up the text, and imagePicker to pick up image that I then store in documents and get the path. I store both of these in a global variables visible in the code above.
My fetch function is :
func coreDataFetch(){
//core data fetch
//1
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
//2
let fetchRequest = NSFetchRequest(entityName: "Entity")
do {
let fetchedResults = try managedContext.executeFetchRequest(fetchRequest) as! [cilj]
listaObjekata = fetchedResults
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
}
I have been through ray wenderlich's article on Core Data, Apple's documentation, a couple of YT videos but I still seem to be missing something. I would greatly appreciate any help. Thanks !
EDIT - here is my cellForRowAtIndexPath
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("myCell") as! cellController
let ciljZaPrikaz = listaObjekata[indexPath.item]
cell.labelText.text = ciljZaPrikaz.imeCilja ?? "no text found"
let path = getDocumentsDirectory().stringByAppendingPathComponent(ciljZaPrikaz.slikaCilja)
cell.imageToShow.image = UIImage(contentsOfFile: path)
return cell
}
You are doing correct but just missing type casting to your model. Try below:
let fetchedResults = try managedContext.executeFetchRequest(fetchRequest)
if let results = fetchResults where results.count > 0 {
let entityModel = results[0] as? Entity
let tekst = entityModel.tekst
}
I would also like to add how I iterate through my return objects from core data:
do {
let fetchedResults = try managedContext.executeFetchRequest(fetchRequest)
listaObjekata.removeAll()
for i in 0...(fetchedResults.count-1) {
let enityModel = fetchedResults[i] as? Entity
let thisToArray = cilj(imeCilja: (enityModel?.tekst!)!, slikaCilja: (enityModel?.slika!)!)
listaObjekata.append(thisToArray)
}
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}

saving Core Data arrays and dictionaries

referring to my previous question: Unique value of object to use in section Swift
my problem now is core data. this is code to save data following the previous code to populate section and table:
let app = UIApplication.sharedApplication().delegate as! AppDelegate
let context = app.managedObjectContext
let entity = NSEntityDescription.entityForName("Movie", inManagedObjectContext: context)!
let movie = Movie(entity: entity, insertIntoManagedObjectContext: context)
movie.title = title.text
movie.plot = plot.text
movie.genre = genre.text
context.insertObject(movie)
do {
try context.save()
} catch {
print("Could not save movie")
}
and fetch data is:
let app = UIApplication.sharedApplication().delegate as! AppDelegate
let context = app.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Movie")
do {
let results = try context.executeFetchRequest(fetchRequest)
self.loadMovie = results as! [Movie]
} catch let err as NSError {
print(err.debugDescription)
}
}
but nothing I receive the error on loadMovie Line..
where am I wrong?
First of all, delete the line
context.insertObject(movie)
because the object has already been inserted in the let movie = line.
To load the movies you need to recreate the data structure using the insertMovie(movie : Movie) function.
let movies = try context.executeFetchRequest(fetchRequest) as! [Movie]
loadMovie.removeAll()
for movie in movies {
insertMovie(movie)
}
As the answer of your previous question suggested, the self.loadMovie now has type [String:[Movie]], so you should probably try casting results as [String:[Movie]].
Try self.loadMovie = results as! [String:[Movie]] instead.

Resources