remove string from coredata swift - ios

i am trying to remove one string from coredata and i created this func:
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if (editingStyle == UITableViewCellEditingStyle.Delete) {
self.statusArray.removeAtIndex(indexPath.row)
self.tableView.reloadData()
// Rimuovo da CoreData
var appDel = UIApplication.sharedApplication().delegate as! AppDelegate
var context : NSManagedObjectContext! = appDel.managedObjectContext!
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
let request = NSFetchRequest(entityName: "Status")
request.returnsObjectsAsFaults = false
let result:NSArray = context.executeFetchRequest(request, error: nil)!
context.deleteObject(result[indexPath.row] as! Status)
context.save(nil)
}
}
but actually this one give me the SIGABRT error when i try to delete something from the tableView! What is wrong with this function?

Try the following example for deleting.It might be helpful.
var request = NSFetchRequest(entityName: "Status")
var new_sync_details = NSEntityDescription.insertNewObjectForEntityForName("Status", inManagedObjectContext: context) as! NSManagedObject
var err: NSErrorPointer?
if var results = context.executeFetchRequest(request, error: nil) as? [Status] {
println("\nResults count: \(results.count)")
for param in results{
println("\nResults param: \(param)")
new_sync_details.managedObjectContext!.deleteObject(param as NSManagedObject)
}
}

Related

Tableview cells not showing up correctly, and core data not loading the saved data correctly

in my app I am trying to create a budgeting app. I have tried creating a custom tableView Cell, but when it is run in the simulator, the tableView is condensed and does not show up correctly. As well as this, I am trying to save and load data from Coredata. However when the viewController loads, the error "Fatal Error: Index Out of Range" appears. I have viewed many coreData tutorials and threads however none of them help with my issue.
I want my tableViews to show up like this: storyboard view
However they appear like this.
Here is my code for the tableView and core data.
Any help is appreciated, thank you!
ViewController
var goals: [NSManagedObject] = []
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return CGFloat(goals.count)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! AllGoalsTableViewCell
let goal = goals[1]
cell.titleLabel?.text = goal.value(forKey: "title") as? String
return cell
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//1
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelegate.persistentContainer.viewContext
//2
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Goal")
//3
do {
goals = try managedContext.fetch(fetchRequest)
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
if !self.goals.isEmpty
{
tableView.reloadData()
}
}
addNewViewController
var goals: [NSManagedObject] = []
func save(title: String, goalAmount: Double, percent: Double, amountPerWeek: Double) {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
//1
let managedContext = appDelegate.persistentContainer.viewContext
//2
let entity = NSEntityDescription.entity(forEntityName: "Goal", in: managedContext)!
let goal = NSManagedObject(entity: entity, insertInto: managedContext)
//3
goal.setValue(title, forKey: "title")
goal.setValue(goalAmount, forKey: "goalAmount")
goal.setValue(percent, forKey: "percent")
goal.setValue(amountPerWeek, forKey: "amountPerWeek")
//4
do {
try managedContext.save()
goals.append(goal)
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
#IBAction func addNewAction(_ sender: Any)
//CoreData
self.save(title: title, goalAmount: goalAmount ?? 0.0, percent: percent, amountPerWeek: amountPerWeekFloat ?? 0.0)
print("saved")
}

Invisible trouble to view the Core Data in TableViewCells

Did from the example: https://drive.google.com/open?id=0B3d4jY23eLOoejdRWkE0SG1VMkk
Step 1. I implemented the Core Data "Database". I have now 17 record and want to view all of them through the Cells in TableView ...
I did as like it was in tutorial, but it doesn't work. I wasted a week, and can't find an error :( It loads perfectly, but data is not displayed in cells :( So...
import Foundation
import CoreData
#available(iOS 10.0, *)
class DatabaseController
{
private init() { }
class func getContext() -> NSManagedObjectContext
{
return persistentContainer.viewContext
}
// MARK: - Core Data stack
static var persistentContainer: NSPersistentContainer =
{
let container = NSPersistentContainer.init(name: "Database")
//let container = NSPersistentContainer(name: "Database")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError?
{
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
class func saveContext ()
{
let context = persistentContainer.viewContext
if context.hasChanges
{
do {
try context.save()
}
catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
Mainly 3 files ... save/get/persistant container in "DatabaseController.swift"
Next "AppDelegate.Swift"...
func applicationWillTerminate(_ application: UIApplication)
{
DatabaseController.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL =
{
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel =
{
let modelURL = Bundle.main.url(forResource: "Database", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? =
{
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("Database.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
do
{
try coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
}
catch {
coordinator = nil
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
let error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict as? [AnyHashable : Any])
NSLog("Unresolved error \(String(describing: error)), \(error.userInfo)")
print(error.localizedDescription)
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? =
{
let coordinator = self.persistentStoreCoordinator
if coordinator == nil
{
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
Main functions responsible for DataCore
And final file for TableView. Before i made it as DataCore , cells were displayed like this
if indexPath.row == 0 {
cell.postImageView.image = UIImage(named: "ENTP")
cell.postTitleLabel.text = "ENTP"
cell.authorLabel.text = "Oleksandr Zheliezniak"
cell.authorImageView.image = UIImage(named: "author"):
} else if indexPath.row == 1 {
cell.postImageView.image = UIImage(named: "INTJ")
cell.postTitleLabel.text = "INTJ"
cell.authorLabel.text = "Gabriel Theodoropoulos"
cell.authorImageView.image = UIImage(named: "appcoda-300")
} else if indexPath.row == 2 {
cell.postImageView.image = UIImage(named: "ENTP")
cell.postTitleLabel.text = "ENTJ"
cell.authorLabel.text = "Gabriel Theodoropoulos"
cell.authorImageView.image = UIImage(named: "appcoda-300")
} else {
cell.postImageView.image = UIImage(named: "СеКс")
cell.postTitleLabel.text = "и виски"
cell.authorLabel.text = "Кокс Карибский))"
cell.authorImageView.image = UIImage(named: "appcoda-300")
}
Final file as below:
//
// PersonTableViewController.swift
//
// Created by Oleksandr Z 2017(c).
//
import UIKit
import Foundation
import CoreData
#available(iOS 10.0, *)
class PersonTableViewController: UITableViewController, NSFetchedResultsControllerDelegate
{
#IBAction func addButtonPressed(_ sender: Any)
{
switchScreen()
}
#IBOutlet weak var menuButton:UIBarButtonItem!
let moc: NSManagedObjectContext? = (UIApplication.shared.delegate as? AppDelegate)?.managedObjectContext
var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult>?
var valueToPass:String!
//override var prefersStatusBarHidden: Bool {return true}
override func viewDidLoad()
{
super.viewDidLoad()
// MARK: - CORE DATA fetching out to the TableView
fetchedResultsController?.delegate = self
fetchedResultsController = NSFetchedResultsController(fetchRequest: IdentitiesFetchRequest(), managedObjectContext: self.moc!, sectionNameKeyPath: nil, cacheName: nil)
do
{
try fetchedResultsController?.performFetch()
}
catch let error as NSError
{
fatalError("Failed to initialize FetchedResultsController: \(error)")
}
//Visualization
if self.revealViewController() != nil
{
self.revealViewController().rearViewRevealWidth = 250
self.revealViewController().frontViewShadowRadius = 10
self.revealViewController().frontViewShadowColor = UIColor.black
self.revealViewController().frontViewShadowOpacity = 1
menuButton.target = self.revealViewController()
menuButton.action = #selector(SWRevealViewController.revealToggle(_:))
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
self.clearsSelectionOnViewWillAppear = true
}
func IdentitiesFetchRequest() -> NSFetchRequest<NSFetchRequestResult>
{
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Identity")
let sortDescriptor = NSSortDescriptor(key: "lastModified", ascending: true)
fetchRequest.predicate = nil
fetchRequest.sortDescriptors = [sortDescriptor]
fetchRequest.fetchBatchSize = 20
fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: moc!, sectionNameKeyPath: nil, cacheName: nil)
fetchedResultsController?.delegate = self
do
{
try fetchedResultsController?.performFetch()
}
catch
{
fatalError("Failed to initialize FetchedResultsController: \(error)")
}
return fetchRequest
}
//MARK: NSFetchedResultsController Delegate Functions
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete { }
switch editingStyle
{
case .delete:
do
{
moc?.delete(fetchedResultsController?.object(at: indexPath) as! Identity)
try moc?.save()
}
catch
{
print(error)
}
case .insert:
break
case .none:
break
}
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?)
{
switch type
{
case NSFetchedResultsChangeType.insert:
tableView.insertRows(at: NSArray(object: newIndexPath!) as! [IndexPath], with: UITableViewRowAnimation.fade)
break
case NSFetchedResultsChangeType.delete:
tableView.deleteRows(at: NSArray(object: indexPath!) as! [IndexPath], with: UITableViewRowAnimation.fade)
break
case NSFetchedResultsChangeType.move:
tableView.deleteRows(at: NSArray(object: indexPath!) as! [IndexPath], with: UITableViewRowAnimation.fade)
tableView.insertRows(at: NSArray(object: newIndexPath!) as! [IndexPath], with: UITableViewRowAnimation.fade)
break
case NSFetchedResultsChangeType.update:
tableView.cellForRow(at: indexPath! as IndexPath)
break
//default:
// break
}
}
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>)
{
tableView.beginUpdates()
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>)
{
tableView.endUpdates()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// Return the number of sections.
return fetchedResultsController?.sections?.count ?? 0
}
//Detailed viewCell
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
print("You selected cell #\(indexPath.row)!")
/*
// Get Cell Label
let indexPath = tableView.indexPathForSelectedRow!
let currentCell = tableView.cellForRow(at: indexPath)! as UITableViewCell
valueToPass = currentCell.textLabel?.text
performSegue(withIdentifier: "yourSegueIdentifer", sender: self)
*/
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if (segue.identifier == "ShowPerson")
{
//var viewController = segue.destination as! PersonDetailViewController
//viewController.passedValue = valueToPass
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return fetchedResultsController?.sections?[section].numberOfObjects ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as!PersonTableViewCell
if let cellContact = fetchedResultsController?.object(at: indexPath) as? Identity
{
cell.textLabel?.text = "\(String(describing: cellContact.pName)), \(String(describing: cellContact.lastModified))"
}
let identityClassName:String = String(describing: Identity.self)
//let typeClassName:String = String(describing: Type.self)
let identity:Identity = NSEntityDescription.insertNewObject(forEntityName: identityClassName, into: DatabaseController.getContext()) as! Identity
//let type:Type = NSEntityDescription.insertNewObject(forEntityName: typeClassName, into: DatabaseController.getContext()) as! Type
let fetchRequest:NSFetchRequest<Identity> = Identity.fetchRequest()
do
{
let searchResults = try DatabaseController.getContext().fetch(fetchRequest)
print("number of results: \(searchResults.count)")
for result in searchResults as [Identity]
{
print("\(result.pName!) is \(result.accuracy)% Robesper. Updeted \(result.lastModified!).")
cell.postImageView.image = UIImage(named: "ENTP")
cell.postTitleLabel.text = identity.pName
cell.authorLabel.text = identity.imType
cell.authorImageView.image = UIImage(named: "author")
}
}
catch { print("Error: \(error)") }
return cell
}
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to toIndexPath: IndexPath) {
}
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
func switchScreen()
{
let mainStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let vc : UIViewController = mainStoryboard.instantiateViewController(withIdentifier: "PersonDetail") as UIViewController
self.present(vc, animated: false, completion: nil)
}
}
Tried solution: Can't show the core data in tableview Swift but it didn't help. Tried all similar topics but can't solve the problem.
You seem to have two separate CoreData stacks: one set up by the DatabaseController class, which uses the viewContext from a NSPersistentContainer (introduced in iOS10), and another set up in the AppDelegate, which uses what looks like standard boilerplate from the older project templates. Your FRC uses the latter, whilst the rest of your code uses the former.
Although these seem to use the same model file, I suspect they are using different persistent stores. I think if you change this line:
fetchedResultsController = NSFetchedResultsController(fetchRequest: IdentitiesFetchRequest(), managedObjectContext: self.moc!, sectionNameKeyPath: nil, cacheName: nil)
to:
fetchedResultsController = NSFetchedResultsController(fetchRequest: IdentitiesFetchRequest(), managedObjectContext: DatabaseController.getContext(), sectionNameKeyPath: nil, cacheName: nil)
your FRC will be using the same context as the code that creates objects, so you should see some results. There are other problems with your code, so as Tom Harrington says in comments, you should learn how to use the debugger to iron them out.
var identities : [Identity] = []
override func viewDidLoad()
{
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
I tried a lot. There is no matter which solution to use (extensions,lazy,direct).
You should create two variables fore sure : ONE for all data array; SECOND for single data in array.
That is the way how it works basically:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as!PersonTableViewCell
let identity = identities[indexPath.row]
cell.postImageView.image = UIImage(named: <picture name>)
cell.postTitleLabel.text = identity.<Your attribute of entity>
cell.authorLabel.text = identity.<Your attribute of entity>
cell.authorImageView.image = UIImage(named: <picture name>)
return cell
}

reload data from core data in swift

I'm trying to fetch data from core data with table view cells, but when the data is reloaded each item in the cell take separate cells, I hope you understand what I mean.
this is the code that I think it has an error
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//1
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
//2
let fetchRequest = NSFetchRequest(entityName: "ShopList")
//3
do {
let results =
try managedContext.executeFetchRequest(fetchRequest)
people = results as! [NSManagedObject]
let results2 =
try managedContext.executeFetchRequest(fetchRequest)
ids = results2 as! [NSManagedObject]
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! itemsList
let shopList = people[indexPath.row]
cell.items!.text = shopList.valueForKey("name") as? String
let shopList2 = ids[indexPath.row]
cell.itemsId!.text = shopList2.valueForKey("logo") as? String
return cell
}
Try this if problem still exists please add code for numberOfRowsInSection in question
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//1
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
//2
let fetchRequest = NSFetchRequest(entityName: "ShopList")
//3
do {
let results =
try managedContext.executeFetchRequest(fetchRequest)
people = results as! [NSManagedObject]
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! itemsList
let shopList = people[indexPath.row]
cell.items!.text = shopList.valueForKey("name") as? String
cell.itemsId!.text = shopList.valueForKey("logo") as? String
return cell
}

how to delete row from coredata (Entity) ios swift

i am new to CORE DATA in my app i am using coredata.
i just stored data in my core data. my entity name is "FEED" and i have a rows with name "title", "id " , "link" ,"desc" so now i want to delete perticular row on based on "id". so how can i do this?
Here is my code,
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell : MessageMusicCell = tableView.dequeueReusableCellWithIdentifier("MessageMusicCell") as! MessageMusicCell
cell.pinButton.tag = indexPath.row
cell.pinButton.addTarget(self, action: #selector(MessageViewController.buttonDeletePressed(_:)), forControlEvents: UIControlEvents.TouchUpInside)
cell.selectionStyle = .None
person = people[indexPath.row]
cell.lbl_title_msg_music.text = person!.valueForKey("title") as? String
cell.img_message_music.image = UIImage(named: "PlaceHolder")
cell.desc_msg_music.text = person!.valueForKey("desc") as? String
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(people.count)
return people.count
}
func buttonDeletePressed(sender:UIButton) {
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell : MessageMusicCell = tableView.dequeueReusableCellWithIdentifier("MessageMusicCell") as! MessageMusicCell
}
so how can i do this?
Try Like this,
func buttonDeletePressed(sender:UIButton) {
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext
let index = sender.tag
context.deleteObject(people[index] as NSManagedObject)
people.removeAtIndex(index)
let _ : NSError! = nil
do {
try context.save()
self.tableView.reloadData()
} catch {
print("error : \(error)")
}
}
Hope this will help you.
func deleteFeed(id:String)
{
let appDelegate =
UIApplication.sharedApplication().delegate as? AppDelegate
let managedContext = appDelegate?.managedObjectContext
let fetchRequest = NSFetchRequest(entityName:"FEED")
fetchRequest.predicate = NSPredicate(format: "id = %#", "\(id)")
do
{
let fetchedResults = try managedContext!.executeFetchRequest(fetchRequest) as? [NSManagedObject]
for entity in fetchedResults! {
managedContext?.deleteObject(entity)
}
}
catch _ {
print("Could not delete")
}
}
Now you can call this function and pass the id whatever you want to delete
func buttonDeletePressed(sender:UIButton){
deleteFeed("1")
}
You can delete data like,
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext!
context.deleteObject(myData[indexPath.row] as NSManagedObject)
myData.removeAtIndex(indexPath.row)
context.save(nil)
this is done from commitEditingStyle so here used indexPath.row. You can pass your id if you want to delete data from other place. If you want to delete data from tableview then you should implement commitEditingStyle and delete data like mentioned above.
Hope this will help :)
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
switch editingStyle {
case .Delete:
// remove the deleted item from the model
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext
context.deleteObject(people[indexPath.row] )
people.removeAtIndex(indexPath.row)
do {
try context.save()
} catch _ {
}
// remove the deleted item from the `UITableView`
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
default:
return
}
}
Hope this could be of some help!

Swift: Deleting core data, table won't update

This code seems to be deleting the actual data ok however the table doesn't update without the row unless I force close the app and reopen.
Thanks in advance.
import UIKit
import CoreData
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
var lists = [NSManagedObject]()
var deleteListIndexPath: NSIndexPath? = nil
#IBOutlet weak var myTableView: UITableView!
#IBAction func addItem(sender: AnyObject) {
let alert = UIAlertController(title: "New List", message: "Add a new list", preferredStyle: .Alert)
let saveAction = UIAlertAction(title: "Save", style: .Default) { (UIAlertAction) -> Void in
let textField = alert.textFields![0] as UITextField
if textField != "" {
self.saveItem(textField.text!)
self.myTableView.reloadData()
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .Default, handler: nil)
alert.addTextFieldWithConfigurationHandler(nil)
alert.addAction(saveAction)
alert.addAction(cancelAction)
presentViewController(alert, animated: true, completion: nil)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return lists.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let myCell:UITableViewCell = myTableView.dequeueReusableCellWithIdentifier("Prototype1")!
let list = lists[indexPath.row]
print(lists[indexPath.row])
myCell.textLabel?.text = list.valueForKey("listTitle") as? String
return myCell
}
override func viewDidLoad() {
super.viewDidLoad()
self.myTableView.dataSource = self
self.myTableView.delegate = self
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName:"List")
// you may need to sort the list
let sortDescriptor1 = NSSortDescriptor(key: "listTitle", ascending: true)
let sortDescriptors = [sortDescriptor1]
fetchRequest.sortDescriptors = sortDescriptors
var fetchedResults : [NSManagedObject] = []
do
{
fetchedResults = try managedContext.executeFetchRequest(fetchRequest) as! [NSManagedObject]
}
catch
{
return
}
for list in fetchedResults
{
lists.append(list)
}
self.myTableView.reloadData()
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if(editingStyle == .Delete ) {
// Find the LogItem object the user is trying to delete
let logItemToDelete = lists[indexPath.row]
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
managedContext.deleteObject(logItemToDelete)
self.myTableView.reloadData()
}
}
func saveItem(Saveitem: String)
{
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let entity = NSEntityDescription.entityForName("List", inManagedObjectContext: managedContext)
let item = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)
item.setValue(Saveitem, forKey: "listTitle")
do {
try managedContext.save()
lists.append(item)
}
catch {
print("Error")
}
}
}
You can use NSFetchedResultsController class with their NSFetchedResultsControllerDelegate protocol methods. And then you can update, delete, insert or move objects very easily!
If your tableView doesn't updated? You can use viewDidAppear function.
I think you still need to remove the "logItem" from the lists object.
lists.removeAtIndex(indexPath.row)
I could give you a more precise answer if you upload the code from this function at the tableview datasource protocol:
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)

Resources