Search code examples
iosswiftcore-datansattributedstring

Swift 4 - How to save NSAttributedstring in core data


In .xcdatamodeld file, I made a attribute content, and make its type transformable. And after creating NSManagedObject Subclass, I found in properties file, the type of content is NSObject? .And now I change NSObject as NSAttributedstring? ,and ran it, build success.But when I save data, this time, a lot of error occurred,these errors is about UIApplication.shared.delegate as! AppDelegate by breakpoint. I think my way to save NSAttributedstring in core data has more problem. How to do this with transformable type? Thanks!


Solution

  • I found the easiest solution for both Obj-c and Swift.

    In Core Data you can add an attribute, For example let's call it attributedText. Then define its type as Transformable. After you create the .h file then change the data type of attributedText from NSDictionary to NSAttributedString.

    Now you can save the NSAttributedString in Core Data.

    Recall it as like this:

    myObject.attributedText
    

    It will return your NSAttributedString.

    For Swift: Try to create a column of Transformable type. Then create your NSManagedObject Subclass, which will in your case be a swift file. Then simply change the type of the column in the file so that you have something like @NSManaged var name: NSAttributedString.

    I hope it can help you.