如何显示已经保存在核心数据中的数据?

Posted

技术标签:

【中文标题】如何显示已经保存在核心数据中的数据?【英文标题】:How to show the data that has already been saved in core data? 【发布时间】:2016-04-06 12:04:19 【问题描述】:

我想显示已经保存在核心数据中的数据,我只想预览它,就像保存书籍名称的数据并在 tableview 上显示一样。到目前为止,我看到的所有教程都是,通常采用文本字段,输入数据,保存然后获取它。请帮助我,因为这是我与核心数据的第一次互动

【问题讨论】:

你需要做更多的研究。您提到的教程向您展示了如何插入数据,因此您可以在没有文本字段的情况下执行此操作。 【参考方案1】:

据我了解,您正在尝试使用 NSfetchedResults 控制器。如果您的数据不是一个数组以将其保存到核心数据,如果您正在使用 swift,请执行以下操作...

//创建你的数组

var employee:NSMutableArray = []
employee.addObject(["name":"Bill","LastName":"Hanks"])
employee.addObject(["name":"Rolex","LastName":"Swarzer"])
employee.addObject(["name":"Clive","LastName":"Martin"])
employee.addObject(["name":"Jimi","LastName":"Hendrix"])

将其添加到核心数据如下:

let appDel = UIApplication.sharedApplication().delegate as! AppDelegate
        let context = appDel.managedObjectContext

        for item in employee 
            do 
                let newUser = NSEntityDescription.insertNewObjectForEntityForName("Employee", inManagedObjectContext: context)
                newUser.setValue(item["name"], forKey: "name")
                newUser.setValue(item["LastName"], forKey: "lastname")
                try context.save()
             catch 
                //do nothing
            
        

假设您知道如何设置 UITableView 并已调用其属性 TableBox 观察以下方法。您可以复制和粘贴,只需更改必要的内容

//---------------------------------------- 加载 tableViewMethods -----

func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? 
    return ""


func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
    let sectionInfo = self.fetchedResultsController.sections![section]
    return sectionInfo.numberOfObjects


func numberOfSectionsInTableView(tableView: UITableView) -> Int 
    return (self.fetchedResultsController.sections?.count)!    

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 
    let cell = tableView.dequeueReusableCellWithIdentifier("theCell", forIndexPath: indexPath)

    let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject
    self.configureCell(cell, withObject: object)

    return cell


func configureCell(cell: UITableViewCell, withObject object: NSManagedObject) 
    cell.textLabel!.text = object.valueForKey("name")!.description
    cell.detailTextLabel!.text = object.valueForKey("lastname")!.description


func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool 
    // Return false if you do not want the specified item to be editable.
    return true


func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool 
    return true


func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) 
    tableBox.moveRowAtIndexPath(sourceIndexPath, toIndexPath: destinationIndexPath)


func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) 
    if editingStyle == .Delete 
        let context = self.fetchedResultsController.managedObjectContext
        context.deleteObject(self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject)

        do 
            try context.save()
         catch 
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate.
            abort()
        
    

//-------- 获取结果控制器 只需记住更改实体名称和 NSSortdescriptor 键即可。还将 tableBox 属性更改为您的名称

var fetchedResultsController: NSFetchedResultsController 
    if _fetchedResultsController != nil 
        return _fetchedResultsController!
    
    let appDel = UIApplication.sharedApplication().delegate as! AppDelegate
    let context = appDel.managedObjectContext
    let fetchRequest = NSFetchRequest(entityName: "Employee")

    // Set the batch size to a suitable number.
    //fetchRequest.fetchBatchSize = 20

    // Edit the sort key as appropriate.
    let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)

    fetchRequest.sortDescriptors = [sortDescriptor]

    // Edit the section name key path and cache name if appropriate.
    // nil for section name key path means "no sections".
    let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
    aFetchedResultsController.delegate = self
    _fetchedResultsController = aFetchedResultsController

    do 
        try _fetchedResultsController!.performFetch()
     catch 
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        //print("Unresolved error \(error), \(error.userInfo)")
        abort()
    

    return _fetchedResultsController!

var _fetchedResultsController: NSFetchedResultsController? = nil

func controllerWillChangeContent(controller: NSFetchedResultsController) 
    self.tableBox.beginUpdates()


func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) 
    switch type 
    case .Insert:
        self.tableBox.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
    case .Delete:
        self.tableBox.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
    default:
        return
    


func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) 
    switch type 
    case .Insert:
        tableBox.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
    case .Delete:
        tableBox.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
    case .Update:
        self.configureCell(tableBox.cellForRowAtIndexPath(indexPath!)!, withObject: anObject as! NSManagedObject)
    case .Move:
        tableBox.moveRowAtIndexPath(indexPath!, toIndexPath: newIndexPath!)
    


func controllerDidChangeContent(controller: NSFetchedResultsController) 
    self.tableBox.endUpdates()

【讨论】:

以上是关于如何显示已经保存在核心数据中的数据?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 ios 中的单元格上显示核心数据?

SwiftUI:如何从核心数据中的 TextField 中保存值

如何更新核心数据中的可转换属性

如何在保存到核心数据之前验证上下文中的值

如何打开保存在我的 in pad 中的数据(使用核心数据模型保存)

核心数据:如何显示 fetchrequest 的结果以计算表格视图单元格中的值