2015-08-08 87 views
0

我的應用程序每次都使用中止函數核心數據崩潰。由於這個代碼,它崩潰了。它有什麼問題?應用程序委託 - 加載核心數據Swift

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

回答

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


     } 
    } 
相關問題