Ошибка доступа к значению Core Data в Swift

Я работал с Core Data. После выполнения выборки и перезагрузки приложение UITableView дает сбой.

 override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell?
    {
        var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

        tasks = self.fetchedResultsController.objectAtIndexPath(indexPath) as Tasks
        cell.textLabel.text = tasks?.desc

        return cell
    }

Я знаю, что ошибка в этой части ->

    tasks = self.fetchedResultsController.objectAtIndexPath(indexPath) as Tasks

После прочтения некоторых вопросов StackOverflow я добавил этот код в свой существующий метод делегата UITableView cellForRowAtIndexPath.

override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell?
    {
        var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

       var array : NSArray = self.fetchedResultsController.fetchedObjects as NSArray
        cell.textLabel.text = array.valueForKeyPath("desc") as NSString

        return cell
    }

В этом месте опять вылетает приложение.

   var array : NSArray = self.fetchedResultsController.fetchedObjects as NSArray

я напечатал это этим кодом

println(self.fetchedResultsController.fetchedObjects)

[<NSManagedObject: 0x16debcc0> (entity: Tasks; id: 0x16dd02f0 <x-coredata://A5AEB550-EB6D-4A47-9F6F-2F3AA49CA6BF/Tasks/p2> ; data: {
    desc = gghjg;
}), <NSManagedObject: 0x16ebb1d0> (entity: Tasks; id: 0x16e8cda0 <x-coredata://A5AEB550-EB6D-4A47-9F6F-2F3AA49CA6BF/Tasks/p1> ; data: {
    desc = gxshli;
})]

Я не знаю, в чем проблема с этим. Я выполнил шаги, описанные в этой статье Пример основных данных.

Если кто-то знает, в чем проблема с этим, пожалуйста, дайте мне знать. Благодарю вас.

Вот изображение для отчета о сбое. введите здесь описание изображения

Вот полный код моего класса исходного файла ViewController.

import UIKit
import CoreData

class MaterTableViewController: UITableViewController, UIAlertViewDelegate, NSFetchedResultsControllerDelegate {

    var fetchedResultsController : NSFetchedResultsController = NSFetchedResultsController()
    let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext
    var tasks : Tasks? = nil


    override func viewDidLoad()
    {
        super.viewDidLoad()

        self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: Selector("insertNewObject"))

        // Update the ViewDidLoad method of TableViewController to populate fetchedResultController variable and set the delegate to self and call the function to retrieve the results.

        fetchedResultsController = getFetchedResultController()
        fetchedResultsController.delegate = self
        fetchedResultsController.performFetch(nil)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    // MARK: - Core Data Methods

    func insertNewObject()
    {
        if tasks != nil
        {
            self.editTasks()
        }
        else
        {
            var alertView : UIAlertView = UIAlertView()
            alertView.title = "Add Note"
            alertView.alertViewStyle = UIAlertViewStyle.PlainTextInput
            alertView.addButtonWithTitle("Cancel")
            alertView.addButtonWithTitle("Save")
            alertView.delegate = self
            alertView.show()

        }

    }

     func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int)
     {
        switch buttonIndex
            {
        case 0 : alertView .dismissWithClickedButtonIndex(buttonIndex, animated: true)
        case 1 :
            tempData = alertView.textFieldAtIndex(0).text
            self.saveThisValue(tempData)
        default : println("Nothin")
        }
    }

    var tempData : NSString = NSString()

    func editTasks()
    {
        tasks?.desc = tempData
        managedObjectContext?.save(nil)
    }

    func saveThisValue(input : NSString)
    {

        let entityDescription = NSEntityDescription.entityForName("Tasks", inManagedObjectContext: managedObjectContext)
        let task = Tasks(entity: entityDescription, insertIntoManagedObjectContext: managedObjectContext)
        task.desc = input
        managedObjectContext?.save(nil)

    }

    func getFetchedResultController() -> NSFetchedResultsController
    {
        fetchedResultsController = NSFetchedResultsController(fetchRequest: taskFetchRequest(), managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
        return fetchedResultsController
    }

    func taskFetchRequest() -> NSFetchRequest
    {
        let fetchRequest  = NSFetchRequest(entityName: "Tasks")
        let sortDecriptor  = NSSortDescriptor(key: "desc", ascending: true)
        fetchRequest.sortDescriptors = [sortDecriptor]
        return fetchRequest
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView!) -> Int {

        return fetchedResultsController.sections.count
    }

    override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {


        return fetchedResultsController.sections[section].numberOfObjects
    }


    override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell?
    {
        var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

        tasks = self.fetchedResultsController.objectAtIndexPath(indexPath) as Tasks
        cell.textLabel.text = tasks?.desc

        return cell
    }


     func controllerDidChangeContent(controller: NSFetchedResultsController!)
     {
        fetchedResultsController.performFetch(nil)
        tableView.reloadData()
    }
}

person Alvin Varghese    schedule 03.09.2014    source источник
comment
У вас есть массив результатов, но cellForRowAtIndexPath предназначен только для одного результата, поэтому вам нужно использовать indexPath.row, чтобы получить конкретный элемент из массива.   -  person Paulw11    schedule 03.09.2014
comment
@ Paulw11 Я пробовал. Но опять показывает ту же ошибку. Не могли бы вы опубликовать код здесь.?   -  person Alvin Varghese    schedule 03.09.2014
comment
Какое сообщение о сбое вы получаете?   -  person Paulw11    schedule 03.09.2014
comment
@Paulw11 Paulw11 я изменил вопрос, пожалуйста, дайте мне свой отзыв.   -  person Alvin Varghese    schedule 03.09.2014
comment
@Элвин Варгезе: твое изображение не очень нам помогает. Когда ваше приложение дает сбой, щелкните вторую, третью и четвертую строку потока 1. Что нам нужно знать, так это сообщения о сбое, связанные с этими строками.   -  person Imanou Petit    schedule 03.09.2014


Ответы (2)


Пытаться

override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell?
{
    var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

    let task = self.fetchedResultsController.objectAtIndexPath(indexPath.row) as Tasks
    cell.textLabel.text = task.desc


    return cell
}
person Paulw11    schedule 03.09.2014
comment
Я сделал. В этой строке отображается ошибка -> let task = self.fetchedResultsController.objectAtIndexPath(indexPath.row) as Tasks // NSNumber не является подтипом NSIndexPath. - person Alvin Varghese; 03.09.2014

я использовал

let ob = self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject
var title : String = ob.valueForKey("keyname")!.description

в недавнем приложении заголовок представлял собой список строк из NSManaged Object

Джеко

person Jacko    schedule 22.10.2014