How to save transformable attribute to Core Data in Swift

Viewed 1083

I'm building a SwiftUI app that fetches movie data from TMDB. When the user adds a movie to their watch list, I'm trying to save the data as a Transformable attribute in Core Data.

The problem is that I am unable to save the data.

Here's my Core Data model enter image description here

I'v created the NSManagedObject NSManagedObject subclass for the TransformableMovie entity:

TransformableMovie+CoreDataClass.swift

import Foundation
import CoreData

@objc(TransformableMovie)
public class TransformableMovie: NSManagedObject {

}

TransformableMovie+CoreDataProperties.swift

import Foundation
import CoreData


extension TransformableMovie {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<TransformableMovie> {
        return NSFetchRequest<TransformableMovie>(entityName: "TransformableMovie")
    }

    @NSManaged public var movie: MovieClass?

}

Here's the class I created:

MovieClass.swift

import Foundation

public class MovieClass: NSObject, NSCoding {
    
    var movie: Movie
    
    init(movie: Movie) {
        self.movie = movie
        
    }
    required public init?(coder aDecoder: NSCoder) {
        self.movie = aDecoder.decodeObject(forKey: "movie") as! Movie

    }
    
    public func encode(with aCoder: NSCoder) {
        aCoder.encode(movie, forKey: "movie")
        
    }
}

And here's the view where I'm attempting to save the data (in navigationBarItems button)

MovieDetailView.swift

import SwiftUI
import CoreData

struct MovieDetailView: View {
    
    @ObservedObject private var detailVM = MovieDetailViewModel()
    
    // Core data
    @Environment(\.managedObjectContext) var managedObjectContext
    
    var movie: Movie
    
    @State private var showingAlert = false
    
    init(movie: Movie) {
        self.movie = movie
        detailVM.getMovieDetails(id: movie.id)
        
        // Stop Scrollview bounce
        UIScrollView.appearance().bounces = false
    }
    
    var body: some View {
        
        VStack {
            
            ...

        }.navigationBarTitle(movie.title)
        
        .navigationBarItems(trailing:
                                Button(action: {
                                    
                                    // Save to core data
                                    let movieToBeSaved = TransformableMovie(context: self.managedObjectContext)
                                    
                                    movieToBeSaved.movie?.movie = detailVM.fetchedMovie!
     
                                    self.showingAlert = true
                                    
                                    do {
                                        try self.managedObjectContext.save()
                                    } catch {
                                        // handle the Core Data error
                                    }
                                }) {
                                    Image(systemName: "plus")
                                        .renderingMode(.original)
                                }.alert(isPresented: $showingAlert) {
                                    Alert(title: Text("Saved"), message: Text("Movie added to your watch list"), dismissButton: .default(Text("Ok")))
                                })
        
    }
}

Any help would be greatly appreciated.

1 Answers

I think the problem is that in this line:

movieToBeSaved.movie?.movie = detailVM.fetchedMovie!

the movie? attribute is nil, so the assignment never works. It’s difficult to see from the code you’ve provided, but I think you need to create a ModelClass object first, and assign that:

let movieModel = ModelClass(movie: detailVM.fetchedMovie)
movieToBeSaved.movie = movieModel
Related