azamsharp
azamsharp

Reputation: 20068

Core Data One to Many Relationship Fetching

When retrieving all reviews for a movie (one-to-many) relationship, which snippet of code would you use and why?

 static func getReviewsByMovieId(movieId: NSManagedObjectID) -> [Review] {
        
        // OPTION 1 
        // SQL call to get movie
        guard let movie = CoreDataManager.shared.getMovieById(id: movieId),
              // SQL call to get reviews for the movie
              let reviews = movie.reviews
              else {
            return []
        }
        
        return (reviews.allObjects as? [Review]) ?? []
        
        
        // OPTION 2
        // SQL call to get reviews for a particular movie
        let request: NSFetchRequest<Review> = Review.fetchRequest()
        request.predicate = NSPredicate(format: "movie = %@", movieId)
        
        do {
            return try CoreDataManager.shared.viewContext.fetch(request)
        } catch {
            return [] 
        }
        
    }

Upvotes: 0

Views: 33

Answers (1)

Tom Harrington
Tom Harrington

Reputation: 70936

Personally I'd do something more like the first, but it's mostly a matter of style. It's very unlikely to matter to performance unless you're doing this a lot. In that case I'd want to try both and profile the results.

I don't know how your getMovieById(id:) works, but if it's using a fetch request I'd suggest replacing it with either object(with:) or existingObject(with:). Both simply look up an object by ID without needing a predicate. The first is probably slightly faster, and the second is safer, so the choice depends on how certain you can be that the object ID is valid.

Upvotes: 1

Related Questions