Right here is an instance:
struct DemoApp: View {
@State var viewModel = DemoAppViewModel()
var physique: some View {
VStack {
DemoMonthView(date: viewModel.monthDate)
DemoDayView(date: viewModel.dayDate) // FIRST
.onTapGesture {
viewModel.dayDate = viewModel.dayDate.addingTimeInterval(86000)
}
DemoDayView(date: viewModel.monthDate) // SECOND
.onTapGesture {
viewModel.monthDate = viewModel.monthDate.addingTimeInterval(1400000)
}
}
}
}
@Observable
class DemoAppViewModel {
var dayDate: Date = Date()
var monthDate: Date = Date()
}
struct DemoMonthView: View {
var date: Date
@FetchRequest non-public var days: FetchedResults //you might want to exchange Day right here with any Entity that can enable to breed the difficulty
init(date: Date) {
self.date = date
_days = FetchRequest(
sortDescriptors: [SortDescriptor(.date, order: .reverse)],
predicate: NSPredicate(worth: true)
)
print("DemoMonthView init is known as") //must be referred to as, however with out physique redraws
// heavy calculations for given month
}
var physique: some View {
if #out there(iOS 17.1, *) {
print("DemoMonthView physique is known as") //shouldn't be referred to as❓
}
return VStack {
Textual content(date.formatted(date: .lengthy, time: .omitted)).font(.title.daring())
}
}
}
struct DemoDayView: View {
var date: Date
var physique: some View {
Textual content(date.formatted(date: .lengthy, time: .omitted))
}
}
#Preview {
DemoApp()
}
Merely, while you faucet FIRST
button it shouldn’t redraw DemoMonthView, nevertheless it does. Why? I actually need to keep away from that by tapping each time FIRST
button. SECOND
button redraws DemoMonthView
view appropriately, what I perceive. However why the FIRST?
After I remark it out days
and _days
affiliation in init, then every part is ok, it DOES NOT redraws…
However that scenario is only a shortened drawback of my actual, extra sophisticated app. There’s a fetchRequest with heavy calculations which shouldn’t be referred to as so steadily like faucet on the button, like right here in instance, when tapping that button doesn’t change something associated to DemoMonthView.
If it’s the purpose as a result of lack of my data, what ought to I do know to keep away from that?
Why it issues right here? As a result of I have to replace that DemoMonthView
ONLY when monthDate
adjustments, not every time when dayDate
adjustments.