SwiftUI:如何使 CoreData 实体符合协议?

问题描述

我是 CoreData 的新手,但设法将其集成到我的项目中。现在我需要我的实体之一符合我创建的协议。我怎样才能做到这一点?我试过了,但我做对了。

我的协议:

protocol MyProtocol {
    init(text: String)
}

CoreData 实体 A:

@objc(A)
public class A: NSManagedobject,MyProtocol {
    
    required init(text: String) {
        super.init()                 // Error!
        self.name = text
    }
    
}

extension A {
    @nonobjc public class func fetchRequest() -> NSFetchRequest<A> {
        return NSFetchRequest<A>(entityName: "A")
    }

    @NSManaged public var id: UUID
    @NSManaged public var name: String
}

extension A : Identifiable,customstringconvertible {
    var description: String { name }
}

更新: 我需要符合 MyProtocol,因为我有一个可重用的视图,它采用一个“对象”数组,这些对象可以向数组添加/删除项目(此更改可能不需要由 CoreData 保留,这些可能只是临时对象)。因此,我需要确保对于我传递给此视图的任何对象,都有一种方法可以使用此最低要求(文本属性)创建相应的实例。请参见下面的示例:

struct ReusableView<Element: My Protocol>: View {
    var data: [Element]

    var body: some View {
        //some code

        Button(action: {
            let newElement = Element(text: "test")
            data.append(newElement)
        },label: {
            Text("Add new Element")
        })

        //more code

        Text("some element name: \(data[0].description)")
    }
}

//... other file

struct MainView: View {
    var entitiesA: [A] //CoreData entity A
    var entitiesB: [B] //CoreData entity B

    var body: some View {
        vstack {
            //some code
            ReusableView(entitiesA)
        
            //some code
            ReusableView(entitiesB)
        }
    }
}

此外,我需要实现协议 customstringconvertible,以便我能够访问“description属性

CoreData 对象的所有内容。这甚至可能吗?我做得对吗?

感谢您的帮助!

解决方法

调用指定的初始化器

public init(entity: NSEntityDescription,insertInto context: NSManagedObjectContext?)

像这样:

let context: NSManagedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType(rawValue: 0)!) // Your context

@objc(A)
public class A: NSManagedObject,MyProtocol {
    
    required init(text: String) {
        super.init(entity: NSEntityDescription.entity(forEntityName: "A",in: context)!,insertInto: context)
        self.name = text
    }
    
}

注意:Cotext 是一个例子。使用上下文