Reputation: 4087
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?
Upvotes: 1
Views: 481
Reputation: 1802
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()
}
Upvotes: 1