我尝试使用 Leaks from Instrument 检查我的应用程序是否存在内存泄漏。事实证明,泄漏指出内存泄漏发生在我的扩展名上:Date。扩展函数在 swiftUI 中的 View 结构内使用到 @Published date: Date 属性从我的 viewModel。难道我做错了什么?我该怎么做才能在扩展中没有强引用?这是我的扩展:
t1
这是具有日期作为属性的结构:
extension Date {
func toString(withFormat customFormat: String = "dd MMM YYYY") -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = customFormat
return dateFormatter.string(from: self)
}
}
我的具有文章数组的 ViewModel:
struct Article: Codable,Hashable {
let source: Source?
let title: String?
let author: String?
let description: String?
let url: String?
let urlToImage: String?
let publishedAt: Date?
let content: String?
}
还有我的主列表视图:
class NewsListViewModel: ObservableObject {
@Published var searchedArticles = [Article]()
@Published var tabsArticles = [Tabs : [Article]] ()
@Published var isSearching = false
@Published var searchText = ""
@Published var selectedTab = Tabs.general
@Published var error: Error?
}
可滚动视图:
struct NewsList: View {
@ObservedObject var viewModel: NewsListViewModel
var body: some View {
NavigationView {
//.....//
ScrollableNewsListView(articles: articles,category: viewModel.selectedTab.rawValue,checkLastCellaction: checkactionForLastCell)
//.....//
}
}
}
我在 LazyVStack 中使用的 cellView:
private struct ScrollableNewsListView: View {
var articles: [Article]
var body: some View {
//.....//
ForEach(articles.indices,id: \.self) { index in
NewsCell(article: articles[index])
.onAppear {
checkLastCellaction(index)
//checkactionForLastCell(index: index)
}
}
//.....//
}
}