Search code examples
iosswiftcore-graphics

How to persist CGPaths to CoreData


I am making a drawing app on iOS and would like to save a users drawing to core data.

I know NSData is an attribute type for CoreData so I was thinking of using that maybe.

My idea is to somehow convert my array of CGPaths to NSData and then save the NSData to Core Data. Does anyone have insight in to how I would do this or a better solution out there?


Solution

  • If you convert your CGPath to a UIBezierPath, that supports NSCoding/NSSecureCoding:

    do {
        let path = UIBezierPath(cgPath: cgPath)
        let data = try NSKeyedArchiver.archivedData(withRootObject: path, requiringSecureCoding: false)
    } catch {
        print(error)
    }
    

    You can also convert Data back to UIBezierPath:

    do {
        if let path = try NSKeyedUnarchiver.unarchivedObject(ofClass: UIBezierPath.self, from: data) {
            let cgPath = path.cgPath
        }
    } catch {
        print(error)
    }