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")
}
}
Related
Right now my code is using NSPredicate or sort descriptor to basically just collect a name. I would like NSPredicate to sort all of the names from a-z thats it.
COREDATAHANDLER
class coreDataHandler: NSObject {
private class func getContext() -> NSManagedObjectContext{
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.persistentContainer.viewContext
}
class func saveObject(username:String, password:String) -> Bool{
let context = getContext()
let entity = NSEntityDescription.entity(forEntityName: "User", in: context)
let managedObject = NSManagedObject(entity: entity!, insertInto: context)
managedObject.setValue(username, forKey: "username")
managedObject.setValue(password, forKey: "password")
do {
try context.save()
return true
} catch {
return false}
}
class func filterData() -> [User]? {
let conttext = getContext()
let fetchRequest:NSFetchRequest<User> = User.fetchRequest()
var user:[User]? = nil
var predicate = NSPredicate(format: "username contains[d] %#" ,"duke")
fetchRequest.predicate = predicate
do {
user = try conttext.fetch(fetchRequest)
return user
}catch {
return user
}
}
VIEWCONTROLLER
user = coreDataHandler.filterData()
for i in user! {
print("Judou : \(i.username!)")
}
If you want your user array to be sorted by username and then password, I would add a class function to your CoreDataHandler class to get a sorted array:
class func getSortedData() -> [User]? {
let conttext = getContext()
let fetchRequest:NSFetchRequest<User> = User.fetchRequest()
var user:[User]? = nil
var nameSort = NSSortDescriptor(key:"username", ascending:true)
var passwordSort = NSSortDescriptor(key:"password", ascending:false)
fetchRequest.sortDescriptors = [nameSort, passwordSort]
do {
user = try conttext.fetch(fetchRequest)
return user
} catch {
return user
}
}
Then in your view controller, use this new function to get the sorted array:
user = coreDataHandler.getSortedData()
for i in user! {
print("Judou : \(i.username!), Password:\(i.password)")
}
In swift 4 or swift 5, you can use
func sortlist(){
//1
guard let appDelegate =
UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext =
appDelegate.persistentContainer.viewContext
//2
let fetchRequest =
NSFetchRequest<NSManagedObject>(entityName: "User")
let sort = NSSortDescriptor(key: "username", ascending: false)
fetchRequest.sortDescriptors = [sort]
//3
do {
let langugeCodes = try managedContext.fetch(fetchRequest)
for result in langugeCodes as [NSManagedObject] {
var username:String = result.value(forKey: "username")! as! String
var password:String = result.value(forKey: "password")! as! String
print("username==>",username)
print("name==>",name)
}
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
}
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")
I want to save my data to core data when a button is clicked here is my action button code now let app = UIApplication.sharedApplication().delegate as! AppDelegate
let context = app.managedObjectContext
let entity = NSEntityDescription.entityForName("Cart", inManagedObjectContext: context)
let cart = Cart(entity: entity!, insertIntoManagedObjectContext: context) but the only problem now is that i dont how to save here is my code to parse json
Alamofire.request(.GET, url!, headers: headers).responseJSON { (response) in
let result = response.result
if response.result.isSuccess{
let jsonObj = JSON(result.value!)
if let x = jsonObj["Items"].array {
x.forEach
{
if let uw = ($0["name"]).string{
print(uw)
let qw = ($0["image"]).string
if let rw = ($0["price"]).int{
if let hu = ($0["id"]).int{
print(hu)
let foo = Rest(name: uw, imageUrl: qw!, price: "₦\(rw)")
self.rest.append(foo)
}
}
}
}
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
actInd.stopAnimating()
}
}
}
So i have an array called rest which is where i want get data for the tableview. I want to save information of each cell tapped into coredata here is a screenshot of the app
So when the sure button is tapped it saves the item to coredata
here is my code incase you neecode
Try this, adapted to your code.
In the portion that you have (...let app=...) replace it by this:
let app2 = UIApplication.sharedApplication().delegate as! UIApplicationDelegate
if let context2 = app2.managedObjectContext {
let cart2 = NSEntityDescription.insertNewObjectForEntityForName("Cart", inManagedObjectContext: context2) as! Cart
cart2.name = self.res.name
cart2.price = self.res.price
cart2.url = self.res.imageUrl
cart2.id = ""
// Perform a save operation
do {
try context2?.save()
} catch {
let saveError = error as NSError
print(saveError)
}
}
Let me know if this works.
Cheers
Just an example here when you want to save your data in coredata. You have to create entity/model and all the setup for core data elements. For details please study https://www.raywenderlich.com/115695/getting-started-with-core-data-tutorial
func saveName(name: String) {
//1
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
//2
let entity = NSEntityDescription.entityForName("Person",
inManagedObjectContext:managedContext)
let person = NSManagedObject(entity: entity!,
insertIntoManagedObjectContext: managedContext)
//3
person.setValue(name, forKey: "name")
//4
do {
try managedContext.save()
//5
people.append(person)
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
}
When I try to add the NSDate to newWorkout; code line:
newWorkout.setValue(currentTime, forKey: "workoutDate")
It returns nil even though when I print currentTime just before the line of code is executed it returns the correct NSDate. The core data in saving is to an entity called Workout, with two attributes workoutTime of type Int16 and workoutDate of type Date.
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext
let newWorkout = NSEntityDescription.insertNewObjectForEntityForName("Workout", inManagedObjectContext: context) as! Workout
let totalTimeConverted = Int16(totalTime)
let currentTime = NSDate()
print(currentTime)
// Add parameters
newWorkout.setValue(NSInteger(totalTimeConverted), forKey: "workoutTime")
newWorkout.setValue(currentTime, forKey: "workoutDate")
do {
try context.save()
} catch {
print("Error saving data")
}
do {
let request = NSFetchRequest(entityName: "Workout")
let results = try context.executeFetchRequest(request)
if results.count > 0 {
for item in results as! [NSManagedObject]{
let time = item.valueForKey("workoutTime")
print(time)
let workoutDate = item.valueForKey("workoutDate")
print(workoutDate)
print(time!, workoutDate!)
}
}
} catch{
print("Error loading data")
}
The entity is "User" which has 2 attributes(email and password). I want to delete a User with the attribute email = "dog#gmail.com". What do I do? I did this far, but I don't know how to delete with attribute. Which means I need to locate the User first then make the delete.
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext!
context.deleteObject(User: NSManagedObject)
context.save(nil)
Thank you in advance
You can use a predicate to limit your fetch to only return the object you want, then you can delete it, here's an example:
let appDel = UIApplication.sharedApplication().delegate as! AppDelegate
let context = appDel.managedObjectContext!
var fetchError : NSError?
let fetchPredicate = NSPredicate(format: "email == %#", "dog#gmail.com")
let fetchUsers = NSFetchRequest(entityName: "User")
fetchUsers.predicate = fetchPredicate
fetchUsers.returnsObjectsAsFaults = false
let fetchedUsers = context.executeFetchRequest(fetchUsers, error: &fetchError) as! [NSManagedObject]
for fetchedUser in fetchedUsers {
var deleteUserError: NSError?
context.deleteObject(fetchedUser)
context.save(&deleteUserError)
}
This should work:
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "User")
if let fetchResults = try!managedObjectContext.executeFetchRequest(fetchRequest) as? [User] {
for (var i=0; i<fetchResults.count; i++) {
if fetchResults[i].email == "dog#gmail.com" {
managedObjectContext.deleteObject(fetchResults[i])
try!managedObjectContext.save()
}
}
}