tom
tom

Reputation: 27

Fetching a relationship from core data swift 4

I have an Artist and album Entity. I am able to retrieve all of the covers from the Album entity. However I cant figure out how to fetch only covers assigned to an specific artist. As far as I understand this should have some kind of Predicate with specific condition to retrieve that. I am trying to work on the core data relationship to retrieve a cover attribute from the Album entity. Please see attached screens from the core data editor. As well as the code I am trying to implement.

var albums = [Album]()
    let request = NSFetchRequest<Album>(entityName: "Album")
    //request.predicate = NSPredicate(format: "recordArtist = %@", albums)
    do {
        albums = try context.fetch(request)
        for cover in albums {
            if ((currentArtist?.name) != nil){
                print(currentArtist.cover)
            }
        }
    }
    catch { print(error)
    }

entity album and artist

Upvotes: 1

Views: 3189

Answers (2)

Joakim Danielson
Joakim Danielson

Reputation: 51945

In your code I see you have an instance of Artist, currentArtist, which means you don't need to do a new fetch request and instead use the relationship to get the album covers.

let albumSet = currentArtist.albums
let covers = albumSet.map($0.cover)

The covers array will now contain all the covers for the artist.

Upvotes: 0

Sagar Chauhan
Sagar Chauhan

Reputation: 5823

You can achieve this by implementing simple predicate based on artist name. see the following code:

var albums = [Album]()
let request = NSFetchRequest<Album>(entityName: "Album")
request.predicate = NSPredicate(format: "recordArtist.name = %@", "<ProvideArtistNameHere>")
do {
    albums = try context.fetch(request)
    if albums.count > 0 {
        // You have found cover
    }
}
catch {
    print("Error = \(error.localizedDescription)")
}

This code will fetch your full albums based on artist name. From album you can get cover.

I hope this will help you.

Upvotes: 1

Related Questions