当我在Swift2中使用CoreData时,我获得了AppDelegate文件的线程1:EXC_BAD_ACCESS

时间:2016-08-22 18:06:36

标签: ios core-data swift2

我是一名刚刚学习iOS的学生,使用CoreData时感觉很糟糕

任何人都可以告诉我错误发生的原因吗?

error picture

import UIKit
import CoreData

class AToZViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

  var baseURL = "monashcaulfield.maps.arcgis.com/apps/webappviewer/index.html?id="

  var managedObjectContext: NSManagedObjectContext


  var wildlifeList: NSArray


  required init?(coder aDecoder: NSCoder){



    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    self.managedObjectContext = appDelegate.managedObjectContext

    self.wildlifeList = NSArray()

    super.init(coder: aDecoder)
  }

  @IBOutlet weak var tableView: UITableView!



    // data for A to Z dictionary

    var name = ["Blue-billed Duck",
                "Brush-tailed Rock-wallaby",
                "Grey-headed Flying-fox",
                "King Quail",
                "Mallee Worm-Lizard",
                "Mountain Pygmy-possum",
                "Pink-tailed Worm-Lizard",
                "Red-chested Button-quail",
                "South-eastern Long-eared Bat"
                ]

    var nameTwo = ["Oxyura australis",
                   "Petrogale penicillata",
                   "Pteropus poliocephalus",
                   "Coturnix chinensis victoriae",
                   "Aprasia aurita",
                   "Burramys parvus",
                   "Aprasia parapulchella",
                   "Turnix pyrrhothorax",
                   "Nyctophilus corbeni"
                  ]

    var pic = [UIImage(named: "004"),
               UIImage(named: "006"),
               UIImage(named: "007"),
               UIImage(named: "002"),
               UIImage(named: "008"),
               UIImage(named: "005"),
               UIImage(named: "009"),
               UIImage(named: "003"),
               UIImage(named: "001")]

    var dist = ["acd6ceac78df451aa046bdea250fb4d4",
                "fef94a3835f844939294bb0a32c473f0",
                "e4e9a00590b2498d866910de81b2f44a",
                "72e59910fc8448c5a1d2a83195361382",
                "87faf8f5e5f84646aa2cd535135863e3",
                "bbc166cc95a244e7bde4da6b0051405e",
                "d43b723f23244ae0882bd618818366fbv",
                "a8b77ed3aa084f6b97485bda3acf8c48",
                "ab6d7601ec2b48d2ad2ba6add73f3591"
                ]





    override func viewDidLoad() {
        super.viewDidLoad()

        let fetchRequest = NSFetchRequest()

        let entityDescription = NSEntityDescription.entityForName("List",  inManagedObjectContext: self.managedObjectContext)

        fetchRequest.entity = entityDescription



        do{
            self.wildlifeList = try self.managedObjectContext.executeFetchRequest(fetchRequest)

            if self.wildlifeList.count == 0

            {
                addWildlifeData()
            }

        }
        catch{
            let fetchError = error as NSError
            print(fetchError)
        }

        // Do any additional setup after loading the view.
    }


  func addWildlifeData(){

    var data = NSEntityDescription.insertNewObjectForEntityForName("List", inManagedObjectContext: self.managedObjectContext)as? List

    data!.id = "a10012"
    data!.name = "King Quail"
    data!.nameTwo = "Coturnix chinensis victoriae"
    data!.dist = "72e59910fc8448c5a1d2a83195361382"
    data!.cata = "ot"
    data!.pic = "002"


    data = NSEntityDescription.insertNewObjectForEntityForName("List", inManagedObjectContext: self.managedObjectContext)as? List

    data!.id = "a10019"
    data!.name = "Red-chested Button-quail"
    data!.nameTwo = "Turnix pyrrhothorax"
    data!.dist = "a8b77ed3aa084f6b97485bda3acf8c48"
    data!.cata = "ot"
    data!.pic = "003"


    saveRecords()




  }



  func saveRecords(){


    do{
        try self.managedObjectContext.save()
        let fetchRequest = NSFetchRequest()
        let entityDescription = NSEntityDescription.entityForName("List", inManagedObjectContext: self.managedObjectContext)
        fetchRequest.entity = entityDescription

        do{
            self.wildlifeList = try self.managedObjectContext.executeFetchRequest(fetchRequest) as! [List]
        }
        catch{
            let fetchError = error as NSError
            print (fetchError)
        }
    }
    catch let error{
        print("Could not save Deletion \(error)")
    }

  }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        //return name.count

        return self.wildlifeList.count
    }


    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = self.tableView.dequeueReusableCellWithIdentifier("AToZCell", forIndexPath: indexPath) as! AToZTableViewCell



        let l: List = self.wildlifeList[indexPath.row] as! List

        cell.label.text = l.name
        cell.labelTwo.text = l.nameTwo

        let picNumber = l.pic

        cell.imagePic.image = UIImage(named: picNumber!)


        return cell
    }





    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {




        if(segue.identifier == "AToZSegue") {

            let indexPathTwo = self.tableView.indexPathForSelectedRow!

            let l: List = self.wildlifeList[indexPathTwo.row] as! List

            let distAddress = l.dist

            let combineURL = self.baseURL + distAddress!

            print(combineURL)

            if let destinationVC = segue.destinationViewController as? ShowDetailSegueViewController{
                destinationVC.currentURL = combineURL



            }
        }




    }





    /*
     // MARK: - Navigation

     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */




    ///let alertController = UIAlertController()



}

1 个答案:

答案 0 :(得分:0)

由于您没有使用NSFetchedResultsController,因此无需在init方法中分配托管对象上下文,这可能导致错误,因为AppDelegate可能尚未初始化。

删除init方法并将代码放入viewDidLoad()

override func viewDidLoad() {
    super.viewDidLoad()
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    self.managedObjectContext = appDelegate.managedObjectContext
}

并使用Swift数组而不是未指定类型NSArray作为数据源

var wildlifeList = [List]()