【问题标题】:Fetching data from Core Data only returns one value从 Core Data 获取数据只返回一个值
【发布时间】:2017-05-08 10:01:16
【问题描述】:

我有这两个功能

//function for updating the group list groupIds
func updateFriendGroupList(friendId: String, groupIds: [String]) {

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    let friendGroups = FriendGroups(context: context)

    for i in 0..<groupIds.count {
        friendGroups.friendId = friendId
        friendGroups.groupId = groupIds[i]
    }

    (UIApplication.shared.delegate as! AppDelegate).saveContext()
}


//function for fetching group list groupIds
func fetchFriendGroupList(friendId: String) -> ([String]) {
    var groupIds = [String]()

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    self.fetchFriendGroupListEntity.removeAll()

    do {
        self.fetchFriendGroupListEntity = try context.fetch(FriendGroups.fetchRequest())
    } catch {
        print("Fetching Failed")
    }

    for i in 0..<self.fetchFriendGroupListEntity.count {
        if self.fetchFriendGroupListEntity[i].friendId == friendId {
            groupIds.append(self.fetchFriendGroupListEntity[i].groupId!)
        }
    }
    //returns an array containing groupIds
    return groupIds
}

我检查了 updateFriendGroupList 中保存的 groupId 的数量。例如 2。但在我的检索函数中,计数始终为 1。

尽管保存了多个 groupId,但每次获取它们时我只得到 1 个 groupId。我错过了什么?

【问题讨论】:

    标签: swift xcode core-data swift3 xcode8


    【解决方案1】:

    在这种情况下,您只创建一个 NSManagedObject 实例,并为同一个对象设置不同的值。要解决您的问题,您应该修改您的第一种方法

    func updateFriendGroupList(friendId: String, groupIds: [String]) {
    
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    
    
    for i in 0..<groupIds.count {
        let friendGroups = FriendGroups(context: context) //here
        friendGroups.friendId = friendId
        friendGroups.groupId = groupIds[i]
    }
    
    (UIApplication.shared.delegate as! AppDelegate).saveContext()
    }
    

    【讨论】:

    • 哇,就是这样。那个 NSManagedObject 实例很棘手。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-29
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2011-01-14
    • 1970-01-01
    相关资源
    最近更新 更多