如何从coredata中的实体获取过滤数据

Posted

技术标签:

【中文标题】如何从coredata中的实体获取过滤数据【英文标题】:How to get filtered data from entities in coredata 【发布时间】:2021-12-24 15:28:04 【问题描述】:

我有一个场景,我知道我需要做什么,但不知道如何在 Swift 中实现它......

我在 CoreData 中有 2 个表,我获取它们的值如下

我需要什么 - 特定用户好友数组中的所有好友

//-----完整代码 手动 CachedUser 类

import Foundation
import CoreData


extension CachedUser 

@nonobjc public class func fetchRequest() -> NSFetchRequest<CachedUser> 
    return NSFetchRequest<CachedUser>(entityName: "CachedUser")


@NSManaged public var name: String?
@NSManaged public var id: String?
@NSManaged public var company: String?
@NSManaged public var isActive: Bool
@NSManaged public var age: Int16
@NSManaged public var email: String?
@NSManaged public var address: String?
@NSManaged public var about: String?
@NSManaged public var registered: String?
@NSManaged public var tags: String?
@NSManaged public var friends: NSSet?

public var wrappedName: String 
    name ?? "Name N/A"


public var wrappedId: String 
    id ?? "id N/A"


public var wrappedCompany: String 
    company ?? "comapny N/A"


public var wrappedIsActive: Bool 
    isActive



public var checkIsActive: String 
    return isActive ? "YES" :"NO"


public var wrappedEmail: String 
    email ?? "email N/A"


public var wrappedAge: Int16 
    age


public var wrappedRegistered: String 
    registered ?? "N/A"




public var cachedFriend: [CachedFriend] 
    let set = friends as? Set<CachedFriend> ?? []
    return set.sorted 
        $0.wrappedName < $1.wrappedName
    

// MARK:为好友生成的访问器 扩展 CachedUser

@objc(addFriendsObject:)
@NSManaged public func addToFriends(_ value: CachedFriend)

@objc(removeFriendsObject:)
@NSManaged public func removeFromFriends(_ value: CachedFriend)

@objc(addFriends:)
@NSManaged public func addToFriends(_ values: NSSet)

@objc(removeFriends:)
@NSManaged public func removeFromFriends(_ values: NSSet)



extension CachedUser : Identifiable 


//-----

//-- 缓存用户

import Foundation
import CoreData


extension CachedFriend 

    @nonobjc public class func fetchRequest() -> NSFetchRequest<CachedFriend> 
        return NSFetchRequest<CachedFriend>(entityName: "CachedFriend")
    

    @NSManaged public var name: String?
    @NSManaged public var id: String?
    @NSManaged public var users: CachedUser?
    
    
    public var wrappedId: String 
        id ?? "Unknown Id"
    
    
    public var wrappedName: String 
        name ?? "Unknown Name"
    
    



extension CachedFriend : Identifiable 


//------

//---SwiftUI查看我要数据的地方,部分好友不显示任何好友

import SwiftUI

struct DetailView: View 
    let users: [CachedUser]
    let user: CachedUser
    @State var friendsArray: [CachedFriend] = []
    @FetchRequest(sortDescriptors: []) var friendsData: FetchedResults<CachedFriend>
    var body: some View 
        Form 
            List 
                Section("Name") 
                    Text(user.wrappedName)
                        .font(.body)
                
                Section("email") 
                    Text(user.wrappedEmail)
                
                Section("Registration Date") 
                    Text(user.wrappedRegistered)
                
                Section("Company") 
                    Text(user.wrappedCompany)
                
                Section("Is Active") 
                    Image(systemName: user.isActive ? "checkmark.circle.fill" : "xmark.octagon.fill")
                        .foregroundColor(user.isActive ? Color.green : Color.red)
                
                
                Section("Friends") 
                    List 
                  
                        ForEach(friendsArray, id:\.self) friend in
                        Text(friend.wrappedName)
                    
                        
                    
                  
                    
                
                
               
                               
                
            
            .onAppear 
                friendsArray = Array(user.cachedFriend)
            
           
           
            
           
            
           
          
        
        
   
    
  

//-----结束 在这里,我附上了一个 CachedUser 实体和 CachedFriend 实体的关系图像。

每个用户都有我从 json 文件中获得的朋友数组,该朋友数组包含名称和 id....

我知道我必须遍历朋友表并过滤与用户朋友数组中同名的所有名称,但我似乎无法做到这一点,我在下面尝试过,但它们不起作用,可以任何人都指向我正确的方向。谢谢

  @State var friendsArray: [CachedFriend] = []
 let user: CachedUser
func findFriend()  
    for allFriend in friendsData 
           
        friendsArray = user.cachedFriend.filter( item in
            item.wrappedId == allFriend.wrappedId
        )
           
    
    
    print(friendsArray.count)

json 示例

[
    
        "id": "50a48fa3-2c0f-4397-ac50-64da464f9954",
        "isActive": false,
        "name": "Alford Rodriguez",
        "age": 21,
        "company": "Imkan",
        "email": "alfordrodriguez@imkan.com",
        "address": "907 Nelson Street, Cotopaxi, South Dakota, 5913",
        "about": "Occaecat consequat elit aliquip magna laboris dolore laboris sunt officia adipisicing reprehenderit sunt. Do in proident consectetur labore. Laboris pariatur quis incididunt nostrud labore ad cillum veniam ipsum ullamco. Dolore laborum commodo veniam nisi. Eu ullamco cillum ex nostrud fugiat eu consequat enim cupidatat. Non incididunt fugiat cupidatat reprehenderit nostrud eiusmod eu sit minim do amet qui cupidatat. Elit aliquip nisi ea veniam proident dolore exercitation irure est deserunt.",
        "registered": "2015-11-10T01:47:18-00:00",
        "tags": [
            "cillum",
            "consequat",
            "deserunt",
            "nostrud",
            "eiusmod",
            "minim",
            "tempor"
        ],
        "friends": [
            
                "id": "91b5be3d-9a19-4ac2-b2ce-89cc41884ed0",
                "name": "Hawkins Patel"
            ,
            
                "id": "0c395a95-57e2-4d53-b4f6-9b9e46a32cf6",
                "name": "Jewel Sexton"
            ,
            
                "id": "be5918a3-8dc2-4f77-947c-7d02f69a58fe",
                "name": "Berger Robertson"
            ,
            
                "id": "f2f86852-8f2d-46d3-9de5-5bed1af9e4d6",
                "name": "Hess Ford"
            ,
            
                "id": "6ba32d1b-38d7-4b0f-ba33-1275345eacc0",
                "name": "Bonita White"
            ,
            
                "id": "4b9bf1e5-abec-4ee3-8135-3a838df90cef",
                "name": "Sheryl Robinson"
            ,
            
                "id": "5890bacd-f49c-4ea2-b8fa-02db0e083238",
                "name": "Karin Collins"
            ,
            
                "id": "29e0f9ee-71f2-4043-ad36-9d2d6789b2c8",
                "name": "Pace English"
            ,
            
                "id": "aa1f8001-59a3-4b3c-bf5e-4a7e1d8563f2",
                "name": "Pauline Dawson"
            ,
            
                "id": "d09ffb09-8adc-48e1-a532-b99ae72473d4",
                "name": "Russo Carlson"
            ,
            
                "id": "7ef1899e-96e4-4a76-8047-0e49f35d2b2c",
                "name": "Josefina Rivas"
            
        ]
    ,

【问题讨论】:

你什么都不用做,一个用户的朋友就是属性user.friends。这是一个集合,所以你可能想做friendsArray = Array(user.friends) 谢谢,我试过了 - public var cachedFriend: [CachedFriend] let set = friends as?设置 ?? [] 返回 set.sorted $0.name! 使用Minimal, Reproducible Example 会更容易调试。将一个简单的核心数据模型与排序所需的最少属性放在一起。 很难阅读评论中发布的代码,但这似乎与我的建议相去甚远 他,我正在更新代码,我在顶部,需要几分钟 【参考方案1】:

您永远不需要在 CoreData FetchRequest 上使用 filter

最好用NSPredicate做过滤

https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreData/index.html

但在这种情况下,用户的所有朋友都在一个变量中。如果你有个人user,你需要做的就是这样......

user.friends.allObjects

【讨论】:

谢谢,我已经用 cmets 更新了问题,在最上面显示了你的名字,因为我使用一种方式来转换朋友作为? Set ,然后当我尝试显示时,在 SwiftUI 视图中,没有错误但也没有输出,请指导 @multiverse 使用将为您提供数组的所有对象 我正在尝试 - 使用 .onAppear friendsArray = Array(user.friends?.allObjects) 给出 - 参数类型 '[Any]?'预期是类的实例或类约束类型错误,我已将其转换为 Array 中的核心数据手动类 as let set = friends as?设置 ?? [] ,但它没有给出任何结果,谢谢 你为什么要把它放到一个不同的变量中。那是不需要的。我使代码行更具体一点。如果没有结果/得到一个空数组,这意味着您没有将任何朋友附加到用户。如果我附在答案上的指南,请寻找关系

以上是关于如何从coredata中的实体获取过滤数据的主要内容,如果未能解决你的问题,请参考以下文章

如何从 Core Data 中的关系相关实体获取属性?

如何过滤从 Core Data 获取的数据?

在 Core Data 中获取过滤的关系

SwiftUI从Core Data实体中获取总项目(SQL术语中的行)计数[重复]

iPhone如何使用NSPredicate按父实体过滤Core Data?

Core Data 如何从实体中检索列