2017-05-08 108 views
0

我有这两种功能获取数据仅返回一个值

//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组id的数量。比如说,例如2.但在我的检索功能中,计数总是为1.

尽管保存了多个groupId,但每次抓取它时都只有1个groupId。我错过了什么?

回答

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

哇,这就是它。 NSManagedObject实例很棘手。 –