仅从 Core Data 获取数据 returns 一个值

Fetching data from Core Data only returns one value

我有这两个功能

//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 中保存的 groupIds 的数量。比方说 2。但在我的检索函数中,计数始终为 1。

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

在这种情况下,您只创建了一个 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()
}