简体   繁体   English

Swift CoreData:显示特定数据的最佳方法?

[英]Swift CoreData: Best approach for showing specific data?

I did search and still can't figure out how to do this: 我做了搜索,但仍然不知道如何执行此操作:

I have a tableViewVC which shows a list (cells) of data retrieved from a CoreData Entity: Person. 我有一个tableViewVC,其中显示了从CoreData实体:人员检索的数据列表(单元格)。 The cell only shows the person name attribute of each data entry. 该单元格仅显示每个数据条目的人员姓名属性。

When I tap the cell (func didSelectRowAtIndexPath), it will go to the detailViewVC where I want to show the values of the rest of the attributes associated to that single data (ie age, gender, address, etc.). 当我点击单元格(func didSelectRowAtIndexPath)时,它将转到detailViewVC,我要在其中显示与该单个数据相关联的其余属性(例如年龄,性别,地址等)的值。

I was originally thinking to pass the string value of the name from VC1 to VC2 and then do some sort of a loop in VC2 to search for the relevant data based on the name attribute, but if the names repeat in the database, this won't work. 我本来是想将名称的字符串值从VC1传递到VC2,然后在VC2中进行某种形式的循环以基于name属性搜索相关数据,但是如果名称在数据库中重复,则不会工作。 Definitely a stupid workaround which won't work. 绝对是个不可行的愚蠢解决方法。

So I am thinking to use a unique ID of each data entry, like ObjectID? 因此,我正在考虑对每个数据条目使用唯一的ID,例如ObjectID? If so, how to do? 如果可以,该怎么办? another better and more efficient way? 另一种更好,更有效的方法?

I am new so please be gentle and patient with me. 我是新来的,所以请对我保持温柔和耐心。 Thanks! 谢谢!

EDIT: 编辑:

VC1 has tableview: VC1具有表视图:

import CoreData

class vc1: UIViewController, UITableViewDataSource, UITableViewDelegate {
    ... ... ...

    var personData = [Person]()

    override func viewDidAppear(animated: Bool) {
        fetchAndSetResults()
        medTableView.reloadData()
    }

    func fetchAndSetResults() {
        let app = UIApplication.sharedApplication().delegate as! AppDelegate
        let context = app.managedObjectContext
        let fetchRequest = NSFetchRequest(entityName: "Person")

        do {
            let results = try context.executeFetchRequest(fetchRequest)
            self.personData = results as! [Person]
        }

        catch let err as NSError {
            print(err.debugDescription)
        }
    }


    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCellWithIdentifier("PersonCell") as? PersonCell {

            let person = personData[indexPath.row]

            cell.configureCell(person) //custom func that shows the string value of attribute "name" of entity "Person" on an IBOutlet label.

            return cell
        }

        else {
            return UITableViewCell()
        }
    }
    ... ...

    // Tapping a cell will present VC2_DetailView.
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let indexPath = tableView.indexPathForSelectedRow;
        let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as! PersonCell

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewControllerWithIdentifier("VC2_DetailView") as! VC2_DetailView

        // Pass person's name in the tapped cell to the label.text in VC2_DetailView.
        vc.receivedPersonName = currentCell.cellPersonName.text

        //vc.view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.6)
        //self.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext

        // Adding dispatch_async to eliminate double tapping on cell. VC2 will be presented.
        dispatch_async(dispatch_get_main_queue(), {
            self.presentViewController(vc, animated: true, completion: nil)
        })
    }
    ... ...

}

With this, VC2 will be presented when a cell is tapped. 这样,将在轻按一个单元格时显示VC2。 What I want to achieve is that VC2 will show other attributes associated to that specific person's name, such as "Age" and "Gender" of entity "Person" and show them in the relevant IBOutlet label in VC2. 我要实现的是,VC2将显示与该特定人的姓名相关的其他属性,例如实体“人”的“年龄”和“性别”,并在VC2中的相关IBOutlet标签中显示它们。

More info: VC1 table has 3 cells: John, Jenny, and Josh. 更多信息:VC1表具有3个单元格:John,Jenny和Josh。 When I click Jenny, VC2 will present and her age and gender will be shown. 当我单击Jenny时,将显示VC2,并显示她的年龄和性别。 Entity "Person" has 3 attributes: "name", "age" and "gender". 实体“人”具有3个属性:“名称”,“年龄”和“性别”。

I am new so, any elaborate explanations are much appreciated! 我是新手,非常感谢您进行详尽的解释!

您可以只传递实体本身。

OK, guys, no-one seemed to be interested in helping me deeper. 好的,伙计们,似乎没人愿意帮助我更深入。 I somehow resolved my problem this way: 我以某种方式解决了我的问题:

  func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    //let indexPath = tableView.indexPathForSelectedRow;
    //let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as! PersonCell

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let vc = storyboard.instantiateViewControllerWithIdentifier("VC2_DetailView") as! VC2_DetailView

    // Pass person's name in the tapped cell to the label.text in VC2_DetailView.

    // Get all data stored in the coredata[indexpath] on the same tapped cell.
    let person = personData[indextPath.row]
    vc.receivedPersonName = person.name
    vc.receivedPersonAge = person.age
    vc.receivedPersonGender = person.sex

    //vc.view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.6)
    //self.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext

    // Adding dispatch_async to eliminate double tapping on cell. VC2 will be presented.
    dispatch_async(dispatch_get_main_queue(), {
        self.presentViewController(vc, animated: true, completion: nil)
    })
}

Basically, I retrieved all properties of a specific data and passed them to VC2. 基本上,我检索了特定数据的所有属性,并将它们传递给VC2。

My next challenge will be how to edit those data and save/update the existing data and avoid creating new or duplicating it. 我的下一个挑战将是如何编辑这些数据并保存/更新现有数据,并避免创建新数据或复制它们。

Thanks all and happy coding! 谢谢大家,祝您编程愉快!

Well, I actually simplified further my code, in order to show the details of the entity on a specific indexpath.row. 好吧,实际上我进一步简化了代码,以便在特定indexpath.row上显示实体的详细信息。

When the cell is clicked: 单击该单元格时:

// Let's try a new method by passing indexpath.row interger.
    let index = indexPath.row
    VC2.receivedIndex = index

Therefore, VC2 will receive the index number of the tapped cell from VC1. 因此,VC2将接收来自VC1的分接单元的索引号。

Then I implemented fetchAndResults() of the entity again in VC2 and simply using the received index number I was able to show all the details of that specific entity in relevant label.text(s). 然后,我再次在VC2中实现了实体的fetchAndResults(),只需使用接收到的索引号,我就能在相关的label.text(s)中显示该特定实体的所有详细信息。

For me, knowing the index number (before I asked you if there was a unique ObjectID, but I believe the index number is the unique ID) is better, so later I can implement the update function of the existing details. 对我来说,知道索引号(在我问您是否有唯一的ObjectID之前,但我相信索引号是唯一的ID)会更好,因此以后我可以实现现有详细信息的更新功能。

Cheers! 干杯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM