skip to Main Content

I used to filter using initializers like this(example):

struct ArticleView: View {
    
    @Environment(.modelContext) private var modelContext    
    @Query private var articleStates: [ArticleState]


    let article: Article
    
    init(article: Article) {
        self.article = article
        _articleStates = Query(filter: #Predicate { $0.articleID == article.id } )
    }
    
    var body: some View {
        ... // SwiftUI view that depends on query data.
    }
}

But now when I use this method my iPhone get hot and the app freezes, even Simulator shows overload of CPU
(https://i.sstatic.net/McqcZapB.png)

That method worked fine in ios 17 but now It doesn’t work anymore. Do you have any solution?

2

Answers


  1. Based on this Answer

    Try this approach using an intermediate property to avoid referencing the
    article model in the predicate.

    struct ArticleView: View {
        @Environment(.modelContext) private var modelContext
        @Query private var articleStates: [ArticleState]
        
        let article: Article
        
        init(article: Article) {
            self.article = article
            let articleID = article.id  // <--- here
            _articleStates = Query(filter: #Predicate { $0.articleID == articleID } )
        }
        
        var body: some View {
            // ... // SwiftUI view that depends on query data.
        }
    }
    
    Login or Signup to reply.
  2. You can try using Lazy loading, that is calling the Query only when needed like this. I think having it in the init could be the reason

    struct ArticleView: View {
        @Environment(.modelContext) private var modelContext
        let article: Article
        //This will only be called when needed
        private var articleStates: [ArticleState] {
            Query(filter: #Predicate { $0.articleID == article.id })
        }
    
        var body: some View {
        // use your articleState here
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search