如何将 fetchRequest 更改为要在 UITableView 中使用的数组

Posted

技术标签:

【中文标题】如何将 fetchRequest 更改为要在 UITableView 中使用的数组【英文标题】:How do you change a fetchRequest to an Array to use in a UITableView 【发布时间】:2015-08-23 16:31:13 【问题描述】:

我想将从 coredata 获取的数据放在 UITableView 中,但我得到了这个“EXC_BAD_INSTRUCTION”。 使用 let swiftBlogs Array 工作得很好,所以有人可以告诉我如何将 fetch 转换为 Array 或者这不是正确的方法吗?

import UIKit
import CoreData

class MainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource 

    @IBOutlet var scrollView: UIScrollView!

    @IBOutlet var timeStampTextField: UITextField!
    @IBOutlet var quickQuoteTextField: UITextField!

    @IBOutlet var tableViewQuickQuote: UITableView!


    let swiftBlogs = ["Ray Wenderlich", "NSHipster", "ios Developer Tips", "Jameson Quave", "Natasha The Robot", "Coding Explorer", "That Thing In Swift", "Andrew Bancroft", "iAchieved.it", "Airspeed Velocity"]

    var tableViewCellArray : Array<AnyObject> = []
    var quickQuoteArray : Array<AnyObject> = []


    override func viewDidLoad() 
        super.viewDidLoad()

    


    override func viewDidAppear(animated: Bool) 
        var appDel: AppDelegate            = UIApplication.sharedApplication().delegate as! AppDelegate
        var context:NSManagedObjectContext = appDel.managedObjectContext!
        var request                        = NSFetchRequest(entityName: "QuickQuote" )
            request.returnsObjectsAsFaults = false
            tableViewCellArray             = context.executeFetchRequest(request, error: nil)!


    

    override func viewWillAppear(animated: Bool) 
        quickQuoteTextField.text = ""
        timeStampTextField.text = ""
    

    @IBAction func clearButton(sender: AnyObject) 
        quickQuoteTextField.text = ""
        timeStampTextField.text = ""
    

    @IBAction func addToQuickQuoteButton(sender: AnyObject) 

        let appDel: AppDelegate            = UIApplication.sharedApplication().delegate as! AppDelegate
        let context:NSManagedObjectContext = appDel.managedObjectContext!
        let ent                            = NSEntityDescription.entityForName("QuickQuote", inManagedObjectContext: context)
        var newQuickQuote                  = QuickQuote(entity: ent!, insertIntoManagedObjectContext: context)
            newQuickQuote.quickQuote       = quickQuoteTextField.text
        context.save(nil)
    


    @IBAction func timeStampButton(sender: AnyObject) 
        timeStamp()

        let appDel: AppDelegate            = UIApplication.sharedApplication().delegate as! AppDelegate
        let context:NSManagedObjectContext = appDel.managedObjectContext!
        let ent                            = NSEntityDescription.entityForName("Time", inManagedObjectContext: context)
        var newTime                        = Time(entity: ent!, insertIntoManagedObjectContext: context)
            newTime.time  = timeStampTextField.text
            newTime.quote = quickQuoteTextField.text
        context.save(nil)
    


    func timeStamp ()
         timeStampTextField.text = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: NSDateFormatterStyle.FullStyle,
         timeStyle: NSDateFormatterStyle.ShortStyle)
    

    // MARK: - Table view data source
     func numberOfSectionsInTableView(tableView: UITableView) -> Int 
        return 1
    


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


    private let stampCellID: NSString = "cell"  //This is the cell itself's identifier.    
     func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 
        let cell = tableView.dequeueReusableCellWithIdentifier(stampCellID as String, forIndexPath: indexPath) as! UITableViewCell

        var data: NSManagedObject = quickQuoteArray[indexPath.row] as! NSManagedObject
            cell.textLabel?.text    = data.valueForKey("quickQuote") as? String


//       let row = indexPath.row
//           cell.textLabel?.text = swiftBlogs[row]

        return cell

    


/*
     func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool 
        return true
    


    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) 

        var appDel: AppDelegate            = UIApplication.sharedApplication().delegate as! AppDelegate
        var context:NSManagedObjectContext = appDel.managedObjectContext!
        if editingStyle == UITableViewCellEditingStyle.Delete 
            let tv = tableView
            context.deleteObject(quickQuoteArray.self[indexPath.row] as! NSManagedObject)
            tv.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)

        

        context.save(nil)
    
*/

     func textFieldShouldReturn(textField: UITextField) -> Bool 
        textField.resignFirstResponder()
        return true
    



【问题讨论】:

我认为你混淆了quickQuoteArraytableViewCellArray,所以quickQuoteArray 总是为零。在viewDidAppear 中,使用quickQuoteArray = context.executeFetchRequest(request, error: nil)! 将其与提取结果一起加载。 我通过添加 fetchRequest 并将其存储到数组中对其进行了重新设计。 我通过将 fetchRequest 添加到 @IBaction addtoquiclquove 按钮并将其存储在数组中来对其进行了重新设计。但是必须将数组更改为 [NSManagedObject] 在 func tableView(tableView: UITableView, cellForRowAtIndexPath 我更改了 var data = 的代码行让 qQuote = tableViewCellArray [indexPath.row] cell.textLabel!.text = qQuote.valueForKey ("quickQuote") as? 字符串 【参考方案1】:

您正在混淆您的数组 swiftBlogs 和 quickQuoteArray。表视图是否尝试访问数组元素quickQuoteArray[indexpath.row] 取决于它是否认为索引已填充,基于来自numberOfRowsInSection 的结果。在numberOfRowsInSection 方法中,您将返回 swiftBlogs 的计数,它始终是您手动输入的 10 个左右的字符串。因此,在您的请求甚至被执行之前,或者视图甚至有机会填充其他任何内容之前,它试图显示您在cellForRowAtIndexPath 中使用的数组中不存在的元素。

简而言之: 始终在 cellForRowAtIndexPath 中使用与在 numberOfRowsInSection 中使用的相同的数组。在这里,您混合了两个不同的数组,quickQuoteArray 和 swiftBlogs。

【讨论】:

以上是关于如何将 fetchRequest 更改为要在 UITableView 中使用的数组的主要内容,如果未能解决你的问题,请参考以下文章

如何将活动 UI 的点击传递到地图片段以将地图更改为 MAP_TYPE_HYBRID

jQuery UI datepicker:如何将下拉列表中的月份名称从短名称更改为长名称?

如何将 .qml 扩展名更改为 .ui 以在 pyqt5 应用程序中使用它

如何将材料ui步进器中的数字更改为字母,如a,b,c,d

使用 CloudKit + CoreData,如何在没有 SwiftUI 的 @FetchRequest 的情况下从远程云更新中更新 UI?

如何将入口点更改为 MFC 应用程序的 _tmain()