我有一个具有手动定义的类。可以在下面看到。

class NewsFeedResponse: NSManagedObject, Cachable {

    @NSManaged var id: String?
    @NSManaged var cachedAt: Date?
    @NSManaged var featuredArticles: Array<FeaturedArticle>?
    @NSManaged var learningMaterials: Array<LearningMaterial>?

    enum CodingKeys: String, CodingKey {
        case featuredArticles
        case learningMaterials
    }

    override init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) {
        super.init(entity: entity, insertInto: context)
    }

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        super.init(entity: NewsFeedResponse.entity(), insertInto: CoreDataManager.shared.getContext())
        do {
            self.cachedAt = Date()
            self.featuredArticles = try container.decode(Array<FeaturedArticle>?.self, forKey: .featuredArticles)
            self.learningMaterials = try container.decode(Array<LearningMaterial>?.self, forKey: .learningMaterials)
        } catch {
            print(error)
        }
    }

    func encode(to encoder: Encoder) throws { }
}


在核心数据模型中,有特色的文章和学习材料在两个方向上都具有一对多的关系。如果将Array更改为Set,这不会导致使用Set的唯一问题是它们没有像Arrays那样排序,因此数据的顺序不一致。还值得注意的是,我没有用@objc标记该类,因为如果我这样做,该对象似乎就不会持久存在,这就是为什么它没有此标记的原因。

除此之外,每当我现在运行我的应用程序时,都会遇到以下崩溃。

2019-08-20 09:51:07.265011+0100 [89304:24860419] [error] error: Property 'featuredArticles' is marked copy on class ‘XXXXX.NewsFeedResponse'.  Cannot generate a copying setter method for NSManagedObject's to-one relationship.
CoreData: error: Property 'featuredArticles' is marked copy on class 'XXXXXXX.NewsFeedResponse'.  Cannot generate a copying setter method for NSManagedObject's to-one relationship.
2019-08-20 09:51:07.265235+0100 XXXXXXX[89304:24860419] -[XXXXXXX.NewsFeedResponse setFeaturedArticles:]: unrecognized selector sent to instance 0x600002d8afd0
2019-08-20 09:51:07.270994+0100 XXXXXXX[89304:24860419] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[XXXXXXX.NewsFeedResponse setFeaturedArticles:]: unrecognized selector sent to instance 0x600002d8afd0'


我不确定如何编写coredata抱怨的二传手。

最佳答案

一对多关系必须声明为(优选非可选)SetNSSet

@NSManaged var featuredArticles: Set<FeaturedArticle>
@NSManaged var learningMaterials: Set<LearningMaterial>


如果您需要订单,则有以下三种选择:


将这两种类型声明为NSOrderedSet(没有Swift等效项),然后选中模型中的Arrangement:Ordered复选框。
添加计算的属性或方法以返回已排序的数组。
使用适当的谓词和排序描述符获取特定NewsFeedResponse的文章和材料。

关于ios - CoreData无法生成getter和setter,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57570093/

10-13 06:29