danielsaidi / RichTextKit

RichTextKit is a Swift SDK that helps you use rich text in Swift and SwiftUI.
MIT License
950 stars 126 forks source link

CoreData transformer example #67

Closed DavidAlvarezDev closed 1 year ago

DavidAlvarezDev commented 1 year ago

Hello! Last one for today.

I was not able to get a clear answer online as to what transformer to use for the NSAttributedString be saved directly to CoreData as a Transformable property. First of all, is this a recommended approach? Any benefits to persisting the data some other way in CoreData?

It has seemed to work for me so far, but I don't know what the best approach it to persist the NSAttributedString.

I thought it would be a common topic, but did not get a good answer. But after much investigation online, I found this code:

import Foundation
import UIKit
import CoreData

@objc(NSAttributedStringTransformer)
class NSAttributedStringTransformer: NSSecureUnarchiveFromDataTransformer {
    override class var allowedTopLevelClasses: [AnyClass] {
        return super.allowedTopLevelClasses + [NSAttributedString.self]
    }
}

Thanks in advanced for your guidance.

David Alvarez info@davidalvarezdev.com

EDIT: I apologize that this issue might not be directly related to the development of your package. I just felt that getting a recommendation from this community would be a the beast approach, and that many would benefit from a post like this here, seeing that it is a very common way to persist data. I am not looking for specific code from anyone, just a thumbs up that this is a approach to persist data is a good idea.

danielsaidi commented 1 year ago

@DavidAlvarezDev You sure have been productive! 😄

Hmmm...I'm not sure. You can get the raw data from the string, which is how I save documents when using a document group, but if you think the above code works and wouldn't mind describing how to use it, I could add a CoreData section to the docs.

karlmira commented 1 year ago

afaik you just need to chose type "Transformable" and add "NSAttributedString" into field "Custom Class". The rest will be done by swift and co. automatically. That's what I do and it works perfectly.

danielsaidi commented 1 year ago

That's great @karlmira - thanks for sharing!

Closing this.