Я работал с 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()
}
}
cellForRowAtIndexPath
предназначен только для одного результата, поэтому вам нужно использоватьindexPath.row
, чтобы получить конкретный элемент из массива. - person Paulw11   schedule 03.09.2014