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

时间:2016-04-06 12:04:20

标签: ios objective-c core-data save tableview

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

1 个答案:

答案 0 :(得分:0)

据我所知,您正在尝试使用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,请遵循以下方法。您可以复制和粘贴,只需更改必要的内容

// ------------------------------------- load tableViewMethods ----- < / p>

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()
}