简体   繁体   English

Core Data可用于保存Codable Struct吗?

[英]Can Core Data be used to save a Codable Struct?

I'm struggling with learning Core Data and was wondering if it's even possible to save a struct that adheres to the Codable protocol to Core Data? 我正在努力学习Core Data,并且想知道是否甚至可以将遵循Codable协议的结构保存到Core Data? Essentially, there is a main struct called "Stories" that links to other structs as well. 从本质上讲,还有一个名为“Stories”的主结构,它也链接到其他结构。

The basic structure of my model is: 我模型的基本结构是:

class GetStories : Codable {

typealias NetworkResponse = (Data?, Error?)->Void
typealias ReadyToSave = ()->Void
typealias RefreshTableView = ()->Void

// MARK: - Instance variables
var dataReturnedByServer : Data?
var stories : Stories?
var delegate: GetStoriesDelegate?  // the delegate stops becoming nil when you assign it as the delegate for ViewController.swift
var coverImages : [UIImage]?

// MARK: - Structs
struct Stories : Codable {
    let userStories : [Story]
    let nextURL : URL
    enum CodingKeys: String, CodingKey {
        case userStories = "stories"
        case nextURL = "nextUrl"
    }
}
struct User : Codable {
    let userName : String
    let userAvatar : String
    let userFullName : String
    enum CodingKeys : String, CodingKey{
        case userName = "name"
        case userAvatar = "avatar"
        case userFullName = "fullname"
    }
}
struct Story : Codable {
    let storyID : String
    let storyTitle : String
    let storyUser : User
    let storyCoverImageURL : String
    enum CodingKeys : String, CodingKey{
        case storyID = "id"
        case storyTitle = "title"
        case storyUser = "user"
        case storyCoverImageURL = "cover"
    }
}

... and then there are some other functions. ......然后还有其他一些功能。

From what I've read, the struct needs to be converted to classes themselves so that they can derive from NSManagedObject. 根据我的阅读,结构需要自己转换为类,以便它们可以从NSManagedObject派生。 Is that the best solution to use Core Data to save the "Stories" struct? 这是使用Core Data保存“Stories”结构的最佳解决方案吗?

Not directly but there are some options. 不是直接但有一些选择。

I will present the one I am using: 我将介绍我正在使用的那个:

You can create model in CoreData similar to your struct with suffix ManagedObject (physically its ManagedObject as it's used by CoreData only), then you can extend the actual ManagedObject and store there your struct. 您可以在CoreData中创建模型,类似于具有后缀ManagedObject的结构(物理上它的ManagedObject,因为它仅由CoreData使用),然后您可以扩展实际的ManagedObject并将结构存储在那里。

The extension for User should look like this: User的扩展名应如下所示:

struct User : Codable {
    let userName : String
    let userAvatar : String
    let userFullName : String
}

extension UserManagedObject {
    var model: User {
        get {
            return User(userName: userName!, userAvatar: userAvatar!, userFullName: userFullName!)
        }
        set {
            self.userName = newValue.userName
            self.userAvatar = newValue.userAvatar
            self.userFullName = newValue.userFullName
        }
    }
}

This solution expects you to make ManagedObject models in CoreData first. 此解决方案希望您首先在CoreData中创建ManagedObject模型。 You can also make the relation ship 1:n and n:n it just takes more time to do it but logic is the same as presented on UserManagedObject . 您还可以建立关系1:nn:n它只需要更多时间来完成它,但逻辑与UserManagedObject显示的相同。

Core Data uses NSManagedObjects or subclasses of NSManagedObject to store data in its backing store, typically a SQLite store. Core Data使用NSManagedObjects或NSManagedObject的子类将数据存储在其后备存储中,通常是SQLite存储。 NSManagedObject is a class not a struct, so if you want to use structs and then save data in Core Data you would need to write some code to copy the data from the struct to a NSManagedObject. NSManagedObject是一个类而不是结构,所以如果你想使用结构然后在Core Data中保存数据,你需要编写一些代码来将数据从结构复制到NSManagedObject。

The preference in Swift is to use structs over classes where possible but if you are working with Core Data it may make more sense to be defining your data as NSManagedObjects (and perhaps making the NSManagedObject subclass codable - google core data and cobable and you'll find a bunch of articles including this one . Swift中的首选项是尽可能在类上使用结构,但是如果您正在使用Core Data,那么将数据定义为NSManagedObjects可能更有意义(并且可能使NSManagedObject子类可编码 - 谷歌核心数据和cobable,你会找到一堆文章, 包括这一篇

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM