SwiftData relationshipKeyPathsForPrefetching not working

relationshipKeyPathsForPrefetching in SwiftData does not seem to work here when scrolling down the list. Why?

I would like all categories to be fetched while posts are fetched - not while scrolling down the list.

struct ContentView: View {
    var body: some View {
        QueryList(
            fetchDescriptor: withCategoriesFetchDescriptor
        )
    }
    
    var withCategoriesFetchDescriptor: FetchDescriptor<Post> {
        var fetchDescriptor = FetchDescriptor<Post>()
        fetchDescriptor.relationshipKeyPathsForPrefetching = [\.category]
        return fetchDescriptor
    }
}
struct QueryList: View {        
    @Query
    var posts: [Post]

    init(fetchDescriptor: FetchDescriptor<Post>) {
        _posts = Query(fetchDescriptor)
    }

    var body: some View {
        List(posts) { post in
            VStack {
                Text(post.title)
                Text(post.category?.name ?? "")
                    .font(.footnote)
            }
        }
    }
}

@Model
final class Post {
    var title: String
    var category: Category?
    
    init(title: String) {
        self.title = title
    }
}

@Model final class Category {
    var name: String
    
    init(name: String) {
        self.name = name
    }
}

By using -com.apple.CoreData.SQLDebug 1, I do see that, although the system indeed does prefetching, accessing an attribute of a prefetched relationship still triggers a fetch, which seems to be unnecessary.

I’d suggest that you file a feedback report – If you do so, please share your report ID here.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

FB16366153 (SwiftData relationshipKeyPathsForPrefetching not working)

SwiftData relationshipKeyPathsForPrefetching not working
 
 
Q