swift 核心数据仅返回1个结果

y0u0uwnf  于 2023-01-25  发布在  Swift
关注(0)|答案(1)|浏览(154)

我以前用过很多次核心数据,但这让我完全不知所措,这非常令人沮丧。
简而言之,我发出了一个返回12个结果的服务器请求,我可以看到这12个结果被迭代并添加到我的核心数据实体(朋友)中。一旦完成,我对朋友实体中的所有结果发出了一个获取请求,它只返回1个结果,似乎总是最后添加的结果。
我的代码如下。
向服务器发出的请求:

func getFriends(token: String) async throws -> Int {
    var request = EndPoints().getFriendsEndPoint()
    request.httpMethod = "GET"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
    let (data, response) = try await URLSession.shared.data(for: request)
    let httpResponse = response as? HTTPURLResponse
    guard (response as? HTTPURLResponse)?.statusCode == 200 else {return httpResponse?.statusCode ?? 0}
    let decodedLocations = try JSONDecoder().decode([FriendsStruct].self, from: data)
    ///Update Locations Core Data record
    self.updateCoreDataFriendsRecords(friendsData: decodedLocations)
    return httpResponse?.statusCode ?? 1000
}

将响应记录保存到Core Data:

func addFriendsDetailsToCoreData(friendsData:[FriendsStruct]) {
    deleteFriendsDetailsData()
    let data = NSEntityDescription.insertNewObject(forEntityName: "Friends", into: self.managedObjectContext) as! Friends
    for items in friendsData {
        data.initials = items.initials
        data.username = items.username
        data.id = items.id
        data.activeEventId = items.activeEventId
        data.email = items.email
        data.firstName = items.firstName
        data.lastName = items.lastName
        data.isInActivity = items.isInActivity
        data.fullName = items.fullName
        print("Adding friend")
    }
    print("saving core data = \(friendsData.count)")
    SaveCoreData().save()
}

最后,从Core Data获取新结果:

let managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext
var fetchedFriendsResults = [Friends]()

func fetchFriends() -> [Friends] {
    fetchedFriendsResults.removeAll()
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Friends")
    let sortDescriptor = NSSortDescriptor(key: "username", ascending: true)
    fetchRequest.sortDescriptors = [sortDescriptor]
    do {
        if let fetchResults = try managedObjectContext.fetch(fetchRequest) as? [Friends] {
                print("Number of items in friends = \(fetchResults.count)")
                for items in fetchResults {
                    print("A Friend - \(items.fullName ?? "Unknown")")
                fetchedFriendsResults = fetchResults
                return fetchedFriendsResults
            }
        }
    }
    catch {
        return fetchedFriendsResults
    }
    return fetchedFriendsResults
}
lyfkaqu1

lyfkaqu11#

这里的问题是,对于这行代码,您只创建了一个对象:

let data = NSEntityDescription.insertNewObject(forEntityName: "Friends", into: self.managedObjectContext) as! Friends

在你的循环中,你多次操作这个对象,并在最后保存一次。2所以CoreData中唯一保存的实体包含了最后一次循环的信息。
可能的解决方案:
将CoreData实体的创建移动到循环中。

for items in friendsData {
    let data = NSEntityDescription.insertNewObject(forEntityName: "Friends", into: self.managedObjectContext) as! Friends
    data.initials = items.initials
    data.username = items.username
    data.id = items.id
    data.activeEventId = items.activeEventId
    data.email = items.email
    data.firstName = items.firstName
    data.lastName = items.lastName
    data.isInActivity = items.isInActivity
    data.fullName = items.fullName
    print("Adding friend")
}

相关问题