我正在使用beta 4 Xcode,只是有一个从主视图以模态方式呈现的字符串项目列表。
var body: some View {
NavigationView {
List {
Section() {
Button(action: {
self.shouldShowModal = true
self.areasModal = true
self.accountsModal = false
}) {
Text("Areas")
}
}
}
}
.sheet(isPresented: $shouldShowModal, onDismiss: {
// on dismiss
}) {
if self.accountsModal {
Text("Accounts")
} else if self.areasModal {
AreaListView()
}
}
}
在AreaListView
中,我有以下内容
class MockModel: BindableObject {
struct MockItem: Identifiable {
var id: String
}
var willChange = PassthroughSubject<Void, Never>()
var items: [MockItem] = [] {
willSet {
self.willChange.send()
}
}
init() {
self.performFetch()
}
func performFetch() {
DispatchQueue.main.async { [weak self] in
self?.items = [MockItem(id: "first"), MockItem(id: "fjirst"), MockItem(id: "fiklkrst"), MockItem(id: "fijlkrst")]
}
}
deinit {
print("deinit")
}
}
在执行获取功能中,我模拟了模型执行后台处理然后需要返回主线程的情况。
,在AreasListView中,我拥有
struct AreaListView: View {
@ObjectBinding var model = MockModel()
var body: some View {
NavigationView {
List {
ForEach(model.items) { (item) -> Text in
return Text(item.id)
}
}
}
}
}
当我第一次打开区域时它工作正常,但是第二次它停止填充列表时。我观察到,然后从performFetch()
中删除了异步,一切正常。我还观察到deinit
不是在关闭modal(sheet)(通过下拉)时调用,而是在第二次打开AreasListView时调用。有人可以解释为什么调度异步导致Mal-function,以及为什么在第二次打开AreasListView时取消初始化吗?非常感谢,
p.s。在将调度异步添加到我的模型时,我也在控制台日志中看到以下错误
=== AttributeGraph: cycle detected through attribute 18 ===
=== AttributeGraph: cycle detected through attribute 18 ===
=== AttributeGraph: cycle detected through attribute 104 ==
我还尝试了以下不使用调度队列的方法
func getItem() -> Future<[MockItem], Never> {
return Future { promise in
let t = [MockItem(id: "first"), MockItem(id: "fjirst"), MockItem(id: "fiklkrst"), MockItem(id: "fijlkrst")]
promise(.success(t))
}
}
func performFetch() {
temp = getItem().eraseToAnyPublisher().receive(on: RunLoop.main)
.sink(receiveValue: { [weak self] (items) in
self?.items = items
})
}