I tried to check my app for memory leaks using Leaks from Instrument. It turns out that the Leaks points out that the memory leak is in on of my extension: Date. The extension function is used inside a View struct in swiftUI to a @Published date: Date property from my viewModel. Am I doing something wrong? What do I have to do to not have a strong reference inside the extension? here is my extension:
extension Date {
func toString(withFormat customFormat: String = "dd MMM YYYY") -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = customFormat
return dateFormatter.string(from: self)
}
}
This is the struct that has a date as a property:
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?
}
My ViewModel that has arrays of Articles:
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?
}
And the My main list view:
struct NewsList: View {
@ObservedObject var viewModel: NewsListViewModel
var body: some View {
NavigationView {
//.....//
ScrollableNewsListView(articles: articles, category: viewModel.selectedTab.rawValue, checkLastCellAction: checkActionForLastCell)
//.....//
}
}
}
StrollableView:
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)
}
}
//.....//
}
}
The cellView that I user inside a LazyVStack:
private struct NewsCell: View {
var article: Article
var body: some View {
VStack(alignment: .leading, spacing: 10) {
HStack {
URLImage(url: imageURL)
.frame(width: 50, height: 50)
.cornerRadius(25)
VStack(alignment: .leading) {
Text(article.author ?? "news_details_unknown_author".localized)
Text(dateString)// <-------- HERE I USE MY DateString that calls .toString() from Date extension
.font(.SFDisplayRegularFont(with: 12))
.foregroundColor(.gray)
}
Spacer()
}
}.padding(.all, 15)
.background(Color.newsCellBackground)
.cornerRadius(10)
}
var dateString: String {
guard let date = article.publishedAt else { return ""}
return date.toString()//<------------ Date.toString()
}
var title: String {
article.title ?? ""
}
}