Fetching data from Core Data only returns one value

Chris Mikkelsen

I have these two functions

//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
}

I have checked the number of groupIds being saved in the updateFriendGroupList. Which is let's say for example 2. But in my retrieve function the count would always be 1.

Despite saving multiple groupId, I only get 1 groupId whenever I fetch them. What did I miss?

PiterPan

in this case you create only one instance of NSManagedObject and you set different values for the same object. To solve your problem you should modify your first method

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related