Ios 如何根据第一个表视图的单击行来分隔第二个表视图的值?

Ios 如何根据第一个表视图的单击行来分隔第二个表视图的值?,ios,swift,core-data,tableview,Ios,Swift,Core Data,Tableview,我是斯威夫特的新手,需要你的帮助 在我的应用程序中,我有两个视图控制器。两者都有一个动态表视图。 第一个视图控制器和他的表显示一些类别(命名组),第二个视图控制器显示一些属于这些类别的对象(命名单个组)。用户可以添加和删除两个表视图中的所有内容。 我将每个表视图中的值保存在一个数组中,并在核心数据中使用两个实体(每个表视图一个实体)。在核心数据中,我将类别/对象的ID保存为UUID,将标题保存为字符串。而且每个UUID都有一个索引,所以每个值都有自己的位置 现在我的问题是: 当我在第一个表视图中

我是斯威夫特的新手,需要你的帮助

在我的应用程序中,我有两个视图控制器。两者都有一个动态表视图。 第一个视图控制器和他的表显示一些类别(命名组),第二个视图控制器显示一些属于这些类别的对象(命名单个组)。用户可以添加和删除两个表视图中的所有内容。 我将每个表视图中的值保存在一个数组中,并在核心数据中使用两个实体(每个表视图一个实体)。在核心数据中,我将类别/对象的ID保存为UUID,将标题保存为字符串。而且每个UUID都有一个索引,所以每个值都有自己的位置

现在我的问题是:

当我在第一个表视图中单击一行时,将显示下一个视图控制器(detailViewController)。我可以添加一些东西,一切都很好。 但当我返回并单击第一个表视图中的另一行时,它在detailViewController上再次显示相同的内容

所以我想我必须为第一个表视图中的每一行分离第二个表视图中的对象。 但我不知道怎么做

我考虑的是根据第一个表视图中行值的索引从secondViewController保存数组。困难在于我将应用程序中的所有内容分离到不同的文件中。因此,核心数据有自己的文件,也有阵列和视图控制器本身的存储

因为这个原因,我不知道你到底需要什么代码。我希望这足够了:

班级

import Foundation

class Group {
    private(set) var groupId    : UUID
    private(set) var groupTitle : String

    init(groupTitle: String) {
        self.groupId    = UUID()
        self.groupTitle = groupTitle
    }

    init(groupId: UUID, groupTitle: String) {
        self.groupId    = groupId
        self.groupTitle = groupTitle
    }
}
类单群

import Foundation

class SingleGroup {
    private(set) var singleGroupId          : UUID
    private(set) var singleGroupName        : String
    private(set) var singleGroupAmount      : Double
    private(set) var singleGroupTimeStamp   : Int64


    init(singleGroupName: String, singleGroupAmount: Double, singleGroupTimeStamp: Int64) {
        self.singleGroupId          = UUID()
        self.singleGroupName        = singleGroupName
        self.singleGroupAmount      = singleGroupAmount
        self.singleGroupTimeStamp   = singleGroupTimeStamp
    }

    init(singleGroupId: UUID, singleGroupName: String, singleGroupAmount: Double, singleGroupTimeStamp: Int64) {
        self.singleGroupId          = singleGroupId
        self.singleGroupName        = singleGroupName
        self.singleGroupAmount      = singleGroupAmount
        self.singleGroupTimeStamp   = singleGroupTimeStamp
    }
}
import CoreData

class SingleGroupStorage {
    static let singleGroupStorage : SingleGroupStorage = SingleGroupStorage()

    private var singleGroupIndexToIdDict : [Int:UUID] = [:]
    private var currentIndex: Int = 0

    private(set) var managedObjectContext : NSManagedObjectContext
    private var managedContextHasBeenSet: Bool = false

    // need to init the ManagedObjectCOntext, it will be overwritten when setManagedContext is called from the view controller
    init() {
        managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType)
    }

    func setManagedContext(managedObjectContext: NSManagedObjectContext) {
        self.managedObjectContext = managedObjectContext
        self.managedContextHasBeenSet = true
        let singleGroups = SingleGroupsCoreDataHelper.readSingleGroupsFromCoreData(fromManagedObjectContext: self.managedObjectContext)
        currentIndex = SingleGroupsCoreDataHelper.countSingleGroup
        for (index, singleGroup) in singleGroups.enumerated() {
            singleGroupIndexToIdDict[index] = singleGroup.singleGroupId
        }
    }

    func addSingleGroup(singleGroupToBeAdded: SingleGroup) {
        if managedContextHasBeenSet {
            // add singlegroup UUID to the dictionary
            singleGroupIndexToIdDict[currentIndex] = singleGroupToBeAdded.singleGroupId
            // call Core Data Helper to create the new single group
            SingleGroupsCoreDataHelper.createSingleGroupInCoreData(singleGroupToBeCreated: singleGroupToBeAdded, intoManagedObjectContext: self.managedObjectContext)
            // increase index
            currentIndex += 1
        }
    }
存储组

import CoreData

class Storage {
    static let storage : Storage = Storage()

    private var groupIndexToIdDict : [Int:UUID] = [:]
    private var currentIndex : Int = 0

    private(set) var managedObjectContext : NSManagedObjectContext
    private var managedContextHasBeenSet: Bool = false

    //need to init the ManageObjectContext, it will be overwritten when setManagedContext is called from the view controller
    init() {
        managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType)
    }


    func setManagedContext(managedObjectContext: NSManagedObjectContext) {
        self.managedObjectContext = managedObjectContext
        self.managedContextHasBeenSet = true
        let groups = CoreDataHelper.readGroupsFromCoreData(fromManagedObjectContext: self.managedObjectContext)
        currentIndex = CoreDataHelper.count
        for (index, group) in groups.enumerated() {
            groupIndexToIdDict[index] = group.groupId
        }
    }


    func addGroup(groupToBeAdded: Group) {
        if managedContextHasBeenSet {
            // add group UUID to the dictionary
            groupIndexToIdDict[currentIndex] = groupToBeAdded.groupId
            // call Core Data Helper to create the new group
            CoreDataHelper.createGroupInCoreData(groupToBeCreated: groupToBeAdded, intoManagedObjectContext: self.managedObjectContext)
            // increase index
            currentIndex += 1
        }
    }
存储单组

import Foundation

class SingleGroup {
    private(set) var singleGroupId          : UUID
    private(set) var singleGroupName        : String
    private(set) var singleGroupAmount      : Double
    private(set) var singleGroupTimeStamp   : Int64


    init(singleGroupName: String, singleGroupAmount: Double, singleGroupTimeStamp: Int64) {
        self.singleGroupId          = UUID()
        self.singleGroupName        = singleGroupName
        self.singleGroupAmount      = singleGroupAmount
        self.singleGroupTimeStamp   = singleGroupTimeStamp
    }

    init(singleGroupId: UUID, singleGroupName: String, singleGroupAmount: Double, singleGroupTimeStamp: Int64) {
        self.singleGroupId          = singleGroupId
        self.singleGroupName        = singleGroupName
        self.singleGroupAmount      = singleGroupAmount
        self.singleGroupTimeStamp   = singleGroupTimeStamp
    }
}
import CoreData

class SingleGroupStorage {
    static let singleGroupStorage : SingleGroupStorage = SingleGroupStorage()

    private var singleGroupIndexToIdDict : [Int:UUID] = [:]
    private var currentIndex: Int = 0

    private(set) var managedObjectContext : NSManagedObjectContext
    private var managedContextHasBeenSet: Bool = false

    // need to init the ManagedObjectCOntext, it will be overwritten when setManagedContext is called from the view controller
    init() {
        managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType)
    }

    func setManagedContext(managedObjectContext: NSManagedObjectContext) {
        self.managedObjectContext = managedObjectContext
        self.managedContextHasBeenSet = true
        let singleGroups = SingleGroupsCoreDataHelper.readSingleGroupsFromCoreData(fromManagedObjectContext: self.managedObjectContext)
        currentIndex = SingleGroupsCoreDataHelper.countSingleGroup
        for (index, singleGroup) in singleGroups.enumerated() {
            singleGroupIndexToIdDict[index] = singleGroup.singleGroupId
        }
    }

    func addSingleGroup(singleGroupToBeAdded: SingleGroup) {
        if managedContextHasBeenSet {
            // add singlegroup UUID to the dictionary
            singleGroupIndexToIdDict[currentIndex] = singleGroupToBeAdded.singleGroupId
            // call Core Data Helper to create the new single group
            SingleGroupsCoreDataHelper.createSingleGroupInCoreData(singleGroupToBeCreated: singleGroupToBeAdded, intoManagedObjectContext: self.managedObjectContext)
            // increase index
            currentIndex += 1
        }
    }
核心数据辅助组

import Foundation
import CoreData

class CoreDataHelper {

    private(set) static var count : Int = 0

    static func createGroupInCoreData(groupToBeCreated: Group, intoManagedObjectContext: NSManagedObjectContext) {

        // create an entity and new group record
        let groupEntity = NSEntityDescription.entity(forEntityName: "Groups", in: intoManagedObjectContext)!

        let newGroupToBeCreated = NSManagedObject(entity: groupEntity, insertInto: intoManagedObjectContext)
        newGroupToBeCreated.setValue(groupToBeCreated.groupId, forKey: "groupId")
        newGroupToBeCreated.setValue(groupToBeCreated.groupTitle, forKey: "groupTitle")

        do {
            try intoManagedObjectContext.save()
            count += 1
        } catch let error as NSError {
            print("Could not save group. \(error), \(error.userInfo)")
        }
    }


    static func readGroupFromCoreData(groupIdToBeRead: UUID, fromManagedObjectContext: NSManagedObjectContext) -> Group? {

        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Groups")

        let groupIdPredicate = NSPredicate(format: "groupId = %@", groupIdToBeRead as CVarArg)
        fetchRequest.predicate = groupIdPredicate

        do {
            let fetchedGroupsFromCoreData = try fromManagedObjectContext.fetch(fetchRequest)
            let groupManagedObjectToBeRead = fetchedGroupsFromCoreData[0] as! NSManagedObject
            return Group.init(
                groupId: groupManagedObjectToBeRead.value(forKey: "groupId") as! UUID,
                groupTitle: groupManagedObjectToBeRead.value(forKey: "groupTitle") as! String)

        } catch let error as NSError {
            // TODO error handling
            print("Could not read group. \(error), \(error.userInfo)")
            return nil
        }
    }
转到detailViewController

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "showDetailSegue" {
            if let indexPath = tableView.indexPathForSelectedRow {
                let navTitle = Storage.storage.readGroup(at: indexPath.row)
                let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
                controller.title = navTitle?.groupTitle
            }
        }
    }
第二个表视图

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        //return objects.count
        return SingleGroupStorage.singleGroupStorage.countSingleGroup()
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SingleGroupsTableViewCell", for: indexPath) as! SingleGroupsTableViewCell

        if let object = SingleGroupStorage.singleGroupStorage.readSingleGroup(at: indexPath.row) {
            cell.singleGroupNameLabel!.text = object.singleGroupName
            cell.singleGroupAmountLabel!.text = String(format: "%.2f", object.singleGroupAmount)
            cell.singleGroupDateLabel!.text = DateHelper.convertDate(date: Date.init(seconds: object.singleGroupTimeStamp))
        }
        return cell
    }
我已经找了几个星期的解决办法,但什么也找不到

希望你能理解我的问题是什么,并有任何解决方法或提示如何解决它

更新:

组-读取(在:)

func readGroup(at:Int)->Group?{
如果managedContextHasBeenSet{
//检查输入索引
如果在<0 | |处>当前索引-1{
//TODO错误处理
打印(“无法读取组”)
归零
}
//从字典中获取组UUID
设groupUUID=groupIndexToIdDict[at]
让groupReadFromCoreData:组?
groupReadFromCoreData=CoreDataHelper.readGroupFromCoreData(groupIdToBeRead:groupUUID!,fromManagedObjectContext:self.managedObjectContext)
返回groupReadFromCoreData
}
归零
}
单组相同

    func readSingleGroup(at: Int) -> SingleGroup? {
        if managedContextHasBeenSet {
            // check input index
            if at < 0 || at > currentIndex - 1 {
                // TODO error handling
                print("Can not read SingleGroups.")
                return nil
            }
            // get single group UUID from dicitionary
            let singleGroupUUID = singleGroupIndexToIdDict[at]
            let singleGroupReadFromCoreData: SingleGroup?
            singleGroupReadFromCoreData = SingleGroupsCoreDataHelper.readSingleGroupFromCoreData(singleGroupIdToBeRead: singleGroupUUID!, fromManagedObjectContext: self.managedObjectContext)
            return singleGroupReadFromCoreData
        }
        return nil
    }
func readSingleGroup(at:Int)->SingleGroup?{
如果managedContextHasBeenSet{
//检查输入索引
如果在<0 | |处>当前索引-1{
//TODO错误处理
打印(“无法读取单个组”)
归零
}
//从Dictionary获取单个组UUID
设singleGroupUUID=singleGroupIndexToIdDict[at]
让singleGroupReadFromCoreData:SingleGroup?
singleGroupReadFromCoreData=SingleGroupsCoreDataHelper.readSingleGroupFromCoreData(singleGroupIdToBeRead:singleGroupUUID!,fromManagedObjectContext:self.managedObjectContext)
返回singleGroupReadFromCoreData
}
归零
}

您提供了很多代码,但遗漏了最重要的方法
readGroup(位于:
。请停止使用那些可怕的objective-c-ish私有(set)变量。这是Swift!如果您想要常量声明常量,请替换
私有(set)var
with
let
。此外,管理存储的所有不同单例类似乎都非常昂贵和繁琐。这些都是从哪里获得的?谢谢你的回答。我添加了read方法(在:)。private(set)我从一个教程中得到的东西,也是所有类的分离。我刚开始学习Swift,所以它似乎是正确的。但我会将所有私有(设置)更改为“let”,谢谢。如果我读对了,你只想管理两个数据元素:一些
对象,对于每个对象,一些
单组
。通常,这将在核心数据中建模为一对类,它们之间有一对多的关系。你不需要这些类中的任何数据来管理它们管理他们或他们的关系…只是你的应用程序想要保存/编辑/显示的数据。这似乎是一个非常有用的提示,非常感谢!我将在核心数据关系方面做一些练习,并尝试在我的项目中实现它。
    func readSingleGroup(at: Int) -> SingleGroup? {
        if managedContextHasBeenSet {
            // check input index
            if at < 0 || at > currentIndex - 1 {
                // TODO error handling
                print("Can not read SingleGroups.")
                return nil
            }
            // get single group UUID from dicitionary
            let singleGroupUUID = singleGroupIndexToIdDict[at]
            let singleGroupReadFromCoreData: SingleGroup?
            singleGroupReadFromCoreData = SingleGroupsCoreDataHelper.readSingleGroupFromCoreData(singleGroupIdToBeRead: singleGroupUUID!, fromManagedObjectContext: self.managedObjectContext)
            return singleGroupReadFromCoreData
        }
        return nil
    }