Diagnosing Memory Issues in an iOS Video Application
BehavioralModel answerLast updated
Investigate and resolve memory-related crashes in an iOS video feed app by distinguishing between kernel terminations, retain cycles, and access violations.
Context
You're maintaining an iOS application that displays a scrollable feed of short videos. Users with older iPhone devices are experiencing frequent crashes after several minutes of scrolling through content. The telemetry data shows two distinct crash patterns:
- Some sessions end abruptly with no crash report and system-level diagnostics showing
EXC_RESOURCEor related memory pressure indicators - Other sessions produce
EXC_BAD_ACCESS (SIGSEGV)crashes with stack traces pointing to asynchronous callback handlers
Your Task
As the engineer assigned to resolve this issue, describe your complete approach to diagnosing and fixing these problems. Your response should cover:
-
Failure Mode Analysis: Explain the fundamental differences between the crash types you're seeing. What does each pattern tell you about the underlying problem?
-
Common Culprits: Identify the coding patterns in video feed applications that typically cause each type of failure. Consider aspects like media caching, asynchronous loading, player lifecycle, and observer patterns.
-
Debugging Strategy: Outline the specific Xcode tools and diagnostic techniques you would employ at each investigation stage. Explain what each tool reveals and when to use it.
-
Validation Approach: Describe how you would verify that your fixes actually resolve the memory issues without introducing new problems.
Provide a technical explanation that demonstrates your understanding of iOS memory management, debugging methodology, and systematic problem-solving.
Hints
Hint 1
Think about the difference between memory that grows until the system intervenes versus memory that's accessed incorrectly
Hint 2
Consider what happens to video frames, decoded images, and player objects when cells scroll off-screen
Hint 3
The absence of a crash stack trace is itself a diagnostic clue about what kind of failure occurred
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Diagnostic Approach for iOS Memory Issues
Understanding the Failure Types
The crash patterns point to fundamentally different problems that require distinct debugging approaches:
System Memory Terminations occur when the application's memory footprint exceeds device limits. The kernel's Jetsam mechanism terminates the process without generating a traditional crash report. These appear as EXC_RESOURCE RESOURCE_TYPE_MEMORY events or show up in JetsamEvent logs. There's no stack trace because the app didn't crash—it was killed by the operating system.
Access Violations (EXC_BAD_ACCESS) happen when code attempts to read or write memory that's invalid—typically freed objects or uninitialized pointers. These produce immediate CPU exceptions with precise stack traces showing where the bad access occurred.
A third category worth noting: termination codes like 0x8badf00d indicate the watchdog killed the app for main thread unresponsiveness, not directly a memory issue, though memory pressure can trigger this indirectly through excessive paging or contention.
Video Feed Memory Antipatterns
Unbounded Caching is the most common footprint issue. A naive implementation might cache decoded frames or thumbnails in a dictionary keyed by index path, never evicting entries. Each full-resolution decoded image consumes width × height × 4 bytes. Video frames live in IOSurface-backed memory, which counts against the app's limit but won't show in standard heap profiling.
Prefetch Without Cancellation: The collection view's prefetching API starts loading future items, but if you don't implement proper cancellation in cancelPrefetchingForItemsAt or cell prepareForReuse, those tasks continue. Each active AVPlayer maintains decoder buffers, and abandoned players accumulate rapidly during fast scrolling.
Strong Reference Cycles occur frequently with closures:
- Periodic time observers:
player.addPeriodicTimeObserver { self.updateUI() }captures self strongly, but the player also retains the block - Notification observers using block-based registration retain the block, which may capture the view controller
- Completion handlers on
selfproperties that captureselfcreate cycles
Weak Reference Misuse causes access violations. Using [unowned self] in an async completion assumes the object will outlive the operation. When a cell is reused or a view controller is dismissed before a decode operation completes, the callback fires with an invalid reference. Similarly, Objective-C assign delegates or unremoved KVO/notification observers lead to callbacks on deallocated objects.
Thread-Unsafe Cache Access: Mutating a shared dictionary from both background decode queues and the main thread corrupts internal data structures, causing crashes far from the actual race condition.
Systematic Investigation Workflow
Step 1: Analyze Field Data
Start with MetricKit's MXAppExitMetric to quantify memory limit exits versus bad access crashes. The Xcode Organizer groups crashes by type. Check the device model distribution—older iPhones have 512MB or less available, while newer models allow 1-2GB.
Step 2: Reproduce Locally
Create an automated UI test that scrolls through the feed continuously on the lowest-spec supported device. Log memory metrics using os_proc_available_memory() and track footprint growth over time with signposts.
Step 3: Profile with Instruments Allocations Use the Mark Generation feature: scroll 20 items, return to the initial state, mark a generation. Repeat several cycles. Persistent growth between identical states indicates leaked or abandoned memory.
Enable the VM Tracker instrument to see IOSurface and IOKit allocations that standard heap tracking misses. Group allocations by call tree to identify which code paths are accumulating memory. Look specifically for:
CVPixelBufferandCGImageinstancesAVPlayerItemand related AVFoundation objects- Cell and view controller instances
Step 4: Capture Memory Graphs After scrolling, navigate away from the feed and trigger a memory graph capture. Count instances of your cell classes, players, and view controllers. Reused cells should be bounded by the visible count plus reuse pool. Background view controllers should be deallocated.
Purple exclamation marks indicate detected retain cycles. Enable Malloc Stack Logging to see the allocation backtrace for each object, revealing where orphaned instances were created.
Step 5: Run the Leaks Instrument This catches unreachable Core Foundation objects and raw allocations that ARC doesn't manage—important for video APIs that use Create-rule functions.
Step 6: Diagnose Access Violations
Enable Zombie Objects (NSZombieEnabled environment variable) to convert mysterious crashes into clear "message sent to deallocated instance" reports. Run Address Sanitizer to catch use-after-free bugs. Use Thread Sanitizer to detect the cache data race.
Concrete Fixes
Cancel Asynchronous Work:
class VideoFeedCell: UICollectionViewCell {
private var imageLoadTask: Task<Void, Never>?
private var observerToken: Any?
func configure(item: VideoItem, player: AVPlayer) {
imageLoadTask = Task { [weak self] in
let thumbnail = await loadThumbnail(for: item.id)
guard let self, !Task.isCancelled else { return }
self.thumbnailView.image = thumbnail
}
observerToken = player.addPeriodicTimeObserver(
forInterval: CMTime(value: 1, timescale: 2),
queue: .main
) { [weak player, weak self] time in
self?.updateProgress(time, player: player)
}
}
override func prepareForReuse() {
super.prepareForReuse()
imageLoadTask?.cancel()
imageLoadTask = nil
if let token = observerToken {
// Must keep reference to player to remove observer
observerToken = nil
}
thumbnailView.image = nil
}
}
Implement Bounded Caching:
class ThumbnailCache {
private let cache = NSCache<NSString, UIImage>()
init() {
cache.countLimit = 50
cache.totalCostLimit = 50 * 1024 * 1024 // 50MB
}
}
Remove Notification Observers:
class FeedViewController: UIViewController {
private var notificationTokens: [Any] = []
override func viewDidLoad() {
super.viewDidLoad()
let token = NotificationCenter.default.addObserver(
forName: UIApplication.didEnterBackgroundNotification,
object: nil,
queue: .main
) { [weak self] _ in
self?.pauseVisiblePlayers()
}
notificationTokens.append(token)
}
deinit {
notificationTokens.forEach {
NotificationCenter.default.removeObserver($0)
}
}
}
Verification Strategy
Automated Testing: Run the scrolling UI test for extended periods (30+ minutes) on physical devices while monitoring:
- Peak memory footprint (should plateau, not grow linearly)
- Frame rate (sustained 60fps indicates no main thread stalls)
os_proc_available_memory()(should remain above critical thresholds)
Manual Verification: Use Instruments during the test to confirm:
- Generation marking shows no persistent growth
- Memory graph has bounded instances
- Leaks instrument reports zero leaks
Regression Prevention: Add MetricKit monitoring to production to track memory limit exits across the fleet. Set up alerts when crash rates exceed baselines for specific iOS versions or device models.
The key insight is recognizing that memory footprint growth and invalid memory access are separate failure modes requiring different tools. Footprint issues need statistical analysis over time with Allocations, while access violations need precise stack traces with sanitizers and zombies.