4

我正在使用 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")
    }
}

在执行 fetch 函数中,我模拟了模型执行后台进程然后我需要返回主线程的情况。

在 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不是在关闭模式(工作表)时(通过下拉)而是在我第二次打开 AreasListView 时调用它。有人可以解释为什么调度异步会导致故障,以及为什么在 AreasListView 的第二次打开时会发生取消初始化?非常感谢,

ps 还将调度异步添加到我的模型时,我在控制台日志中看到以下错误

=== 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
            })
    }
4

0 回答 0