2017-05-08 119 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實例很棘手。 –