Swiftui CPU High Usage on Real-Time Foreach View Updating (Macos)

Xcode 13.2 SwiftUI Preview Crashes

Solved by adding ZStack in Preview struct solved it.. This is maybe a bug.
Solution

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ZStack {
ContentView()
}
}
}

SwiftUI Bug - List changes lock UI - (OLD TITLE: SwiftUI CoreData fetch is very slow)

Here's the work around, which, may I add is completely unacceptable. It makes the app technically work, but is so slow, it feels like loading Windows 10 on an 8086. ridiculous.

Also, still no answer or even acknowledgement from Apple Feedback. And my code level support request was debited even though they stated they could not help me. Not happy..

Anyway, if you want to build an app that feels like its digging through mud, using CoreData and being able to search that data, here's your workaround..

1st:
Create a hashable model of your data, or at least the part of the data that you will need to search and/or display:

struct MyDataModel: Hashable {
let title: String
let name: String
let myData: String
}

2nd:
Create an ObservableObject class that publishes a variable which contains an array of your data's model class you just created:

class MyData:ObservableObject {
@Published var searchDataArray = [MyDataModel]()
}

3rd:
make sure you push your environment variable to the views you plan to use this is:
(This example is in my SceneDelegate.swift file

let myData = MyData()

and append .environmentObject(myData) to whatever view you need it in.

4th:
Access the Env Var from your view: @EnvironmentObject var myData: MyData and load your fetch results to the published data array, i used this function to complete the task:

func arrayFiller(){ 

if self.myData.searchDataArray.count > 0 {
self.myData.searchDataArray.removeAll()
}

for item in self.fetchRequest {
self.myData.searchDataArray.append(MyDataModel(title: item.title!, name: item.name!, myData: item:myData!))
}
}

Finally, from the view you want to search, you can iterate your published env var and you can clear the array in between changes to the search criteria with a delay to avoid the bug.

ForEach(self.myData.searchDataArray, id: \.self) { fetchedItem in
Text(fetchedItem.name)
}

Then, I use an .onReceive to watch my searchTerm variable for changes, wipe the published Array, wait 10 milliseconds and refill the array with the data that matches my search terms.

Its really slow and hideous. It works, but I don't think I could go anywhere near production with this mess.



Related Topics



Leave a reply



Submit