App Delegate - 加载核心数据Swift

时间:2015-08-08 16:57:42

标签: ios swift core-data

每次使用中止功能核心数据时,我的应用都会崩溃。它因此代码而崩溃。这有什么问题?

     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()

2 个答案:

答案 0 :(得分:1)

您的代码中未添加用于tableview的委托。

在视图控制器中添加这些

    class MyWordsTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{

在viewDidLoad中添加此代码

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

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

对于核心数据,请尝试以下代码

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)
   }
}

答案 1 :(得分:0)

试试这个,为我工作(swift 2 Xcode 7 beta 5):(我做了更改以适合您的代码)

    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()


        }
  }