Skip to content

Commit 05048e4

Browse files
authored
Fix memory leak: return early on image cache hit in MessageImageView (#93)
The .task block checked NSCache on cache hit but never returned, causing getMediaContent to be called on every channel visit even for already-cached images. The fix always fetches raw data via the SDK (which hits its own disk cache on repeat loads, avoiding network requests), then skips the expensive decode step (toOrientedImage) when the NSImage is already in the NSCache. Two caching layers serve different purposes: - NSCache (checked in init): synchronously pre-populates `image` before the view appears, preventing flicker on scroll/revisit. The image is already on screen before .task runs its disk read. - SDK media cache (getMediaContent): avoids network re-fetches. Always called so `imageData` is populated for drag-and-drop, regardless of whether the decoded NSImage is cached. Fixes #89
1 parent 48b3c80 commit 05048e4

1 file changed

Lines changed: 14 additions & 5 deletions

File tree

Mactrix/Views/ChatView/MessageImageView.swift

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -93,14 +93,23 @@ struct MessageImageView: View {
9393
return
9494
}
9595

96-
let cacheKey = NSString(string: content.source.url())
97-
if let cached = MatrixClient.imageCache.object(forKey: cacheKey) {
98-
image = Image(nsImage: cached)
99-
}
100-
96+
// Two caching layers serve different purposes:
97+
// - NSCache (checked in init): synchronously pre-populates `image` before the
98+
// view appears, preventing flicker on scroll/revisit. Also skips the expensive
99+
// decode step (toOrientedImage) on repeat loads below.
100+
// - SDK media cache (getMediaContent): avoids network re-fetches. Always called
101+
// here so `imageData` is populated for drag-and-drop, even when the decoded
102+
// NSImage is already in the NSCache.
101103
do {
102104
let data = try await matrixClient.client.getMediaContent(mediaSource: content.source)
103105
imageData = data
106+
107+
let cacheKey = NSString(string: content.source.url())
108+
if let cached = MatrixClient.imageCache.object(forKey: cacheKey) {
109+
image = Image(nsImage: cached)
110+
return
111+
}
112+
104113
let nsImage = try data.toOrientedImage(contentType: contentType)
105114
MatrixClient.setCachedImage(nsImage, forKey: cacheKey)
106115
image = Image(nsImage: nsImage)

0 commit comments

Comments
 (0)