gpt4 book ai didi

amazon-dynamodb - 如何在 SwiftUI 中使用 ObservableObject 加载数据?

转载 作者:行者123 更新时间:2023-12-05 06:22:37 25 4
gpt4 key购买 nike

我正在尝试将一个应用程序从 UIKit 转换到 SwiftUI,这取决于基本的 DynamoDB 资源,但我在强制 View 在数据添加到列表时刷新时遇到了障碍。我在这组代码上花费了数小时尝试不同的事情,我想我可能会看看是否有人知道为什么“SessionsData”似乎被丢弃并且不会累积“Sessions”对象。

有没有人有任何快速的想法???

class SessionsData: ObservableObject {

let didChange = PassthroughSubject<SessionsData, Never>()
@Published var data: [Sessions] = [] {
didSet {
didChange.send(self)
}
}

init() {
load()
}

func load() {
let dynamoDBObjectMapper = AWSDynamoDBObjectMapper.default()
let scanExpression = AWSDynamoDBScanExpression()
scanExpression.limit = 20

var temp : [Sessions] = []

dynamoDBObjectMapper.scan(Sessions.self, expression: scanExpression).continueWith(block: { (task:AWSTask<AWSDynamoDBPaginatedOutput>!) -> Any? in
if let error = task.error as NSError? {
print("The request failed. Error: \(error)")
} else if let paginatedOutput = task.result {
for session in paginatedOutput.items as! [Sessions] {
print("Item Found")
temp.append(session)
}
DispatchQueue.main.async {
self.data = temp
self.didChange.send(self)
}
}
print(self.data.count)
return true
})
}
}
struct Events: View {

@ObservedObject var sessionsData = SessionsData()


var body: some View {...}
}

最佳答案

看起来您使代码过于复杂了。 PassthroughSubject 是不必要的。每当您更改 @Published 属性时,它都应该触发更新。

class SessionsData: ObservableObject {

@Published var data: [Sessions] = []

init() {
load()
}

func load() {
let dynamoDBObjectMapper = AWSDynamoDBObjectMapper.default()
let scanExpression = AWSDynamoDBScanExpression()
scanExpression.limit = 20

var temp : [Sessions] = []

dynamoDBObjectMapper.scan(Sessions.self, expression: scanExpression).continueWith(block: { (task:AWSTask<AWSDynamoDBPaginatedOutput>!) -> Any? in
if let error = task.error as NSError? {
print("The request failed. Error: \(error)")
} else if let paginatedOutput = task.result {
for session in paginatedOutput.items as! [Sessions] {
print("Item Found")
temp.append(session)
}
DispatchQueue.main.async {
self.data = temp
}
}
print(self.data.count)
return true
})
}
}

关于amazon-dynamodb - 如何在 SwiftUI 中使用 ObservableObject 加载数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59098343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com