Skip to content

fix(ios): attach the hosting controller outside view callbacks - #1268

Open
mozzius wants to merge 2 commits into
callstack:mainfrom
mozzius:fix/ios-defer-hosting-controller-containment
Open

mozzius wants to merge 2 commits into
callstack:mainfrom
mozzius:fix/ios-defer-hosting-controller-containment

Conversation

@mozzius

@mozzius mozzius commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #1267.

PagerViewProvider adds its UIHostingController as a child of the nearest view controller, and moves or removes it, from inside view callbacks: didMoveToWindow, willMove(toWindow:), willMove(toSuperview:), didMoveToSuperview and layoutSubviews. Those callbacks can run while UIKit is enumerating that view controller's children. For example:

  1. Showing or hiding the status bar makes UIKit walk the view controller tree to update safe area insets (_recursiveUpdateContentOverlayInsetsFromParentIfNecessary).
  2. In that walk, react-native-screens' SafeAreaView sends an unstable_Immediate state update, which commits and mounts the React tree synchronously.
  3. If the mount includes a new pager, addChild runs mid-enumeration, and UIKit throws Collection <__NSArrayM> was mutated while being enumerated.

The issue has the full lldb stack and a repro.

This PR keeps adding the hosting view to the provider immediately, so nothing renders late. Every containment change now goes through updateParentViewController(to:):

  • Same parent: returns right away, so layoutSubviews costs nothing.
  • Moving from one parent to another: happens synchronously, as before. SwiftUI can rebuild the page controller around a nested pager, and UIKit checks the hosting controller's parent as soon as its view moves to a window ([iOS] Nested PagerView crashes with UIViewControllerHierarchyInconsistency (8.0.4) #1098).
  • Attaching to the first parent, or detaching: queued for the next main queue turn (coalesced), and the parent is worked out again at that point. These are the calls that hit the enumeration crash. A hosting controller without a parent passes UIKit's hierarchy check, so its view renders in the meantime.
  • Unmounted pagers: the block holds the hosting controller strongly, so a pager that is unmounted and deallocated before the block runs still detaches its controller.

The behavior from #1204 stays the same: off-window the controller is detached, and inside window-level containers such as FullWindowOverlay, where there's no view controller in the responder chain, it isn't attached to anything.

Test Plan

Repro: https://github.com/mozzius/pager-view-statusbar-crash-repro (Expo SDK 58, RN 0.88.1, react-native-screens 4.30.1, iPad (A16) simulator, iOS 27.2). Each press of Crash shows or hides the status bar and remounts a PagerView that sits outside the navigator.

  • Before: crashes on the 2nd press with the stack from the issue.
  • After: hundreds of remounts without a crash, and paging still works.
  • Nested pagers: the repro's nested-pager screen (an outer pager whose page count changes, with an inner pager in each page) passes. An earlier revision of this PR that also deferred re-parenting crashed there (see the review thread).
  • Appearance: _printHierarchy shows every pager hosting controller appeared, with the right parent, after cold launch, push/pop, remounts and background/foreground. That's the same as 10.0.3, and old controllers don't pile up.
  • In the Bluesky app, on the same change backported to 9.0.11: the original crash sequence no longer reproduces on iPad and iPhone SE simulators, and the Home feeds, profile and lightbox pagers behave as before.

What's required for testing (prerequisites)?

An iPad or iPhone SE simulator. On Face ID iPhones, hiding the status bar doesn't change the top safe area, so the walk doesn't happen.

What are the steps to reproduce (after prerequisites)?

Run the repro and press Crash a few times.

Compatibility

OS Implemented
iOS ✅
Android ❌ (not affected)

Checklist

  • I have tested this on a device and a simulator (simulator so far)
  • I added the documentation in README.md (not needed)
  • I updated the typed files (TS and Flow) (not needed)

UIKit can be enumerating the parent view controller's children when
the provider's view callbacks run, e.g. while it propagates safe area
insets after a status bar change and a synchronous React mount adds a
pager. Calling addChild/removeFromParent there throws
"Collection was mutated while being enumerated". Attach, move and
detach on the next main queue turn instead.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

A child-count change can rehost a retained inner pager before its controller containment is updated, potentially triggering a UIViewControllerHierarchyInconsistency crash.

1 open issue
What changed in this PR

This PR addresses #1267 by moving iOS pager controller attachment and removal outside view callbacks, avoiding mutations while UIKit traverses the controller hierarchy during safe-area updates.

Changes:

  • Defers and coalesces containment updates on the main queue, resolving the target parent when they run.
  • Keeps hosting-view insertion immediate, including in controller-free window overlays.
  • Retains the hosting controller until deferred cleanup completes, even if the provider is deallocated.
File Description
ios/​PagerViewProvider.swift Replaces synchronous containment updates with deferred parent synchronization and cleanup.

Review effort: Balanced

Comment thread ios/PagerViewProvider.swift Outdated
super.willMove(toWindow: newWindow)
if newWindow != nil {
syncParentViewController(to: reactViewController())
scheduleParentViewControllerSync()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, confirmed. With the first version, the nested-pager screen I added to the repro (outer pager whose page count changes, inner pagers in each page) crashed in _associatedViewControllerForwardsAppearanceCallbacks:performHierarchyCheck:isRoot: from _UIHostingView.swiftui_insertManagedSubview, which is #1098.

Fixed in 89afa05. Moving the hosting controller from one parent to another is synchronous again, the same as before this PR. Only attaching it to its first parent and detaching it are deferred, which are the calls that hit the enumeration crash. A hosting controller without a parent passes UIKit's hierarchy check, so deferring those is safe.

Re-ran the repro on an iPad simulator (iOS 27.2):

nested pagers (add/remove pages) status bar + remount
10.0.3 ✅ ❌ crash
first version ❌ crash (#1098) ✅
89afa05 ✅ ✅

_printHierarchy also shows every pager hosting controller appeared, with the right parent, after push/pop, remounts and background/foreground.

UIKit checks the hosting controller's parent as soon as its view moves
to a window, so moving it into a page controller that SwiftUI rebuilt
around a nested pager can't wait (callstack#1098). Only attaching to the first
controller and detaching are deferred.
@troZee

troZee commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

@apex-sentinel-staging review

@apex-sentinel-staging

apex-sentinel-staging Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Apex Sentinel · ✅ Approve · review of 89afa05

No open findings.

🔕 1 dismissed finding, not raised again
Finding Dismissed by
🟡 Coalescing flag discards updateParentViewController requests that carry a specific parent @troZee

To raise one again, reply @apex-sentinel-staging note ... in its thread. It stays dismissed only if Sentinel's re-check withdraws it.

2 findings below minor hidden (user_settings.min_severity).

Reviewed with this repository's own Sentinel configuration (3a44ca5c9446).

💬 Talking to Sentinel

In a finding's thread, reply with:

Command What it does
@apex-sentinel-staging note <context> Adds context; Sentinel re-checks the cited code
@apex-sentinel-staging pivot <why> Says the finding is wrong; Sentinel re-checks the cited code
@apex-sentinel-staging like Marks the finding as useful
@apex-sentinel-staging dislike <why> Marks it as not useful, so it is not raised again

On this conversation, comment @apex-sentinel-staging review to run a full review once again.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 1 new finding on 89afa05. The verdict and the full list are in the summary comment.

Comment thread ios/PagerViewProvider.swift Resolved

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[iOS] Crash "Collection was mutated while being enumerated" when a PagerView mounts during a status bar safe area update

3 participants