I want to update my core-data entity and my code is:
let ff: Cart!
let indexPath = self.tableView?.indexPathForSelectedRow
ff = self.cart[indexPath!.row]
let app = UIApplication.sharedApplication().delegate as! AppDelegate
let context = app.managedObjectContext
let entity = NSEntityDescription.entityForName("Cart", inManagedObjectContext: context)
let cartt = Cart(entity: entity!, insertIntoManagedObjectContext: context)
cartt.name = ff.name
cartt.price = Double(ff.price!)
cartt.rest_id = ff.rest_id
cartt.longg = ff.longg
cartt.latt = ff.latt
cartt.item_id = ff.item_id
cartt.restName = ff.restName
cartt.cookTime = ff.cookTime
ff.setValue(Int(txt.text!), forKey: "quantity")
do{
try context.save()
self.viewDidLoad()
print(cartt.longg)
print(cartt.delivery)
print("saved")
}catch{
print("could not save")
}
The element is updating in the core data, but it is also adding a new row to my tableView with an empty data.
If you want to update quantity of the current object ff try with these lines.
let ff: Cart!
let indexPath = self.tableView?.indexPathForSelectedRow
ff = self.cart[indexPath!.row]
let app = UIApplication.sharedApplication().delegate as! AppDelegate
let context = app.managedObjectContext
ff.setValue(Int(txt.text!), forKey: "quantity")
do{
try context.save()
self.viewDidLoad() // why you call this line here ?
print(cartt.longg)
print(cartt.delivery)
print("saved")
}catch{
print("could not save")
}
Why did you call self.viewDidLoad()?
On your next code, you was creating a new item rather than just updating the current one.
Related
How can i restrict duplicate entry in core data
//MARK:- save in core data
let appDel1:AppDelegate = UIApplication.shared.delegate as! AppDelegate
let context:NSManagedObjectContext = appDel1.persistentContainer.viewContext
let userObj:NSManagedObject = NSEntityDescription.insertNewObject(forEntityName: "RPAData", into: context)
userObj.setValue(rpaType, forKey: "rpatype")
userObj.setValue(rpaReg, forKey: "rparegistration")
userObj.setValue(identificationNumber, forKey: "identificationnumber")
userObj.setValue(rpaTypeId, forKey: "rpatypeid")
do{
try context.save()
print("rpaReg , identificationNumber , rpaTypeId and rpaType Saved in core Data...")
} catch {
print("Error in save - ", error)
}
If the combination of all the 4 entries(rpaReg , identificationNumber , rpaTypeId and rpaType) are same than these data will not save in core data and an alert will be shown.
this is how i fetch data from core data
var dataArray:[NSManagedObject] = []
let appDel1:AppDelegate = UIApplication.shared.delegate as! AppDelegate
let context:NSManagedObjectContext = appDel1.persistentContainer.viewContext
let fetchRequest:NSFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "RPAData")
do
{
dataArray = try context.fetch(fetchRequest) as! [NSManagedObject]
} catch {
print("error =>",error)
}
Add some constraints in your entity
Then use this to show error when saving failure (default value)
context.mergePolicy = NSErrorMergePolicy
I am building an app, in which I want to populate UITableViewCell from CoreData. In CoreData I am able to save data from server and also able to fetch data. But when my internet is offline I am unable to retrive data from CoreData or there is no data in CoreData. How can I fetch last saved data from CoreData when my internet is offline?
I am saving data using following function:
func SetPremiumValues(Array : NSArray){
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let entity = NSEntityDescription.entityForName("PremiumJob", inManagedObjectContext:managedContext)
for i in Array{
let PremiumJob = NSManagedObject(entity: entity!,insertIntoManagedObjectContext: managedContext)
if let rowData :NSDictionary = i as? NSDictionary{
PremiumJob.setValue(rowData["company"], forKey: "company")
PremiumJob.setValue(rowData["city"], forKey: "city")
PremiumJob.setValue(rowData["id"], forKey: "id")
let ImageName = rowData["user_logo"] as? String
let image = "http://dev.jobsmarket.pk/uploads/user-logo/"+ImageName!
let url = NSURL(string: image)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
if let data = NSData(contentsOfURL: url!) {
PremiumJob.setValue(data, forKey: "user_logo")
}
}
PremiumJob.setValue(rowData["title"], forKey: "title")
PremiumJob.setValue(rowData["fe_short_description"], forKey: "fe_short_description")
}
do {
try managedContext.save()
print("saving premium job is this \(PremiumJob)")
self.Premium.append(PremiumJob)
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
}
}
// fetching data using fetch request
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "PremiumJob")
do{
let results = try managedContext.executeFetchRequest(fetchRequest)
for ManagedObject in results {
let managedObjectData : NSManagedObject = ManagedObject as! NSManagedObject
print("premium data from fetch request \(managedObjectData)")
}
}
catch{
}
}
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)")
}
}
I am making a list app and have a Coredata model with two attributes in it (One for item and one for details)
I can save and input data and it will be displayed correctly but when i close and reopen the app, everything has its own cell.
Any help guys?
Code For CellAtIndex
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")! as UITableViewCell
let item = listItems[indexPath.row]
let detailed = detailedItems[indexPath.row]
cell.textLabel?.text = item.valueForKey("item") as? String
cell.detailTextLabel?.text = detailed.valueForKey("detail") as? String
return cell
}
Code For ViewWillAppear
verride func viewWillAppear(animated: Bool) {
//Load First Item
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchrequest = NSFetchRequest(entityName: "ListEnt")
do{
let results = try managedContext.executeFetchRequest(fetchrequest)
listItems = results as! [NSManagedObject]
detailedItems = results as! [NSManagedObject]
}catch{
print("Error")
}
}
Here is the code for saving, I have a dialog box appear, with to text field, and each text field has its own save function
//Saving Items//
func saveItem(itmToSave: String){
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let entity = NSEntityDescription.entityForName("ListEnt", inManagedObjectContext: managedContext)
let item = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)
item.setValue(itmToSave, forKey: "item")
do{
try managedContext.save()
listItems.append(item)
}catch{
print("Saving Main Item")
}
}
//Saving Details
func saveItem2(itmToSave2: String){
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let entity = NSEntityDescription.entityForName("ListEnt", inManagedObjectContext: managedContext)
let item2 = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)
item2.setValue(itmToSave2, forKey: "detail")
do{
try managedContext.save()
detailedItems.append(item2)
}catch{
print("Saving deatil Item")
}
}
Pictures of the problem
How it looks when you input data (Correct way)
How it looks when you close and reopen the app
Cheers Guys
I'm doing save a list of data into core data by using the for each loop here. However, it only helping me to save the last data in the for loop into core data, what problem is it? I couldn't manage to save all the data into core data. Below is my code that I'm working on it...
let appDelegate : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context : NSManagedObjectContext = appDelegate.managedObjectContext
let category = NSEntityDescription.insertNewObjectForEntityForName("Category", inManagedObjectContext:context)
RestApiManager.sharedInstance.makeGetRequest("testingserver", onCompletion: {json in
for result in json["record"].arrayValue
{
print(result)
let id = result["mc_termid"].stringValue
let name = result["mc_name"].stringValue
let parent = result["mc_parent"].stringValue
let color = result["mc_color"].stringValue
let update = result["mc_updated"].stringValue
let termName = result["mc_termname"].stringValue
let status = result["mc_status"].stringValue
category.setValue(id, forKey: "mc_termid")
category.setValue(name, forKey: "mc_name")
category.setValue(parent, forKey: "mc_parent")
category.setValue(color, forKey: "mc_color")
category.setValue(update, forKey: "mc_updated")
category.setValue(termName, forKey: "mc_termname")
category.setValue(status, forKey: "mc_status")
}
do
{
try context.save()
print("Category save to local database successfully.")
}
catch
{
}
})
You need to insert an managedobject every time you iterate one element in the array.
So put the category declaration into the iterating block.
let appDelegate : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context : NSManagedObjectContext = appDelegate.managedObjectContext
RestApiManager.sharedInstance.makeGetRequest("testingserver", onCompletion: {json in
for result in json["record"].arrayValue
{
let category = NSEntityDescription.insertNewObjectForEntityForName("Category", inManagedObjectContext:context)
print(result)
let id = result["mc_termid"].stringValue
let name = result["mc_name"].stringValue
let parent = result["mc_parent"].stringValue
let color = result["mc_color"].stringValue
let update = result["mc_updated"].stringValue
let termName = result["mc_termname"].stringValue
let status = result["mc_status"].stringValue
category.setValue(id, forKey: "mc_termid")
category.setValue(name, forKey: "mc_name")
category.setValue(parent, forKey: "mc_parent")
category.setValue(color, forKey: "mc_color")
category.setValue(update, forKey: "mc_updated")
category.setValue(termName, forKey: "mc_termname")
category.setValue(status, forKey: "mc_status")
}
do
{
try context.save()
print("Category save to local database successfully.")
}
catch
{
}
})