jayReb
jayReb

Reputation: 1

App Delegate - Load Core Data Swift

My app crashes every time using the abort function- core data. It crashes because of this code. What is wrong with it?

     import UIKit
     import CoreData

   class MyWordsTableViewController: UITableViewController, NSFetchedResultsControllerDelegate {


var myList: Array<AnyObject> = []


override func viewDidLoad() {
    super.viewDidLoad()


    let appDel = UIApplication.sharedApplication().delegate as! AppDelegate
    let context = appDel.managedObjectContext
    let freq = NSFetchRequest(entityName: "List")

    do {
   try myList = context.executeFetchRequest(freq)

    } catch {
     print("error")
    }

    tableView.reloadData()

Upvotes: 0

Views: 1222

Answers (2)

Try this, worked for me (swift 2 Xcode 7 beta 5): (I did changes to fit your code)

    import UIKit
    import CoreData

    var myList: Array<AnyObject> = []

    class MyWordsTableViewController: UITableViewController, NSFetchedResultsControllerDelegate
    {
        override func viewDidLoad()
        {

              super.viewDidLoad()

        }

        override func viewDidAppear(animated:Bool)
        {
            //reference to app delegate

            let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

            //reference NSManaged object context

            let context: NSManagedObjectContext = appDel.managedObjectContext!


            let freq = NSFetchRequest(entityName: "List")


            do
            {
                try myList = context.executeFetchRequest(freq)


                NSLog("Number of rows (App): \(myList.count)") 
            } catch _ { NSLog("That went badly...") }

            tableView.reloadData()


        }
  }

Upvotes: 0

Karlos
Karlos

Reputation: 1661

Delegate for tableview are not added in your code.

Add these in your view controller

    class MyWordsTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{

Add this code in your viewDidLoad

   self.Tablename.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")

    Tablename.dataSource = self
    Tablename.delegate = self
    searchBar.delegate = self

For core data try the following code

var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context: NSManagedObjectContext = appDel.managedObjectContext!

var fetchRequest = NSFetchRequest(entityName: "List")

if let fetchResults = appDel.managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as? [NSManagedObject] {
   if fetchResults.count != 0{

     println(fetchResults)
   }
}

Upvotes: 1

Related Questions