atereshkov
atereshkov

Reputation: 4565

Dismissing UIViewController in UIAlertController Action causes a crash

I have just a simple UIAlertController and I show it by a button click:

let alert = UIAlertController(title: "", message: NSLocalizedString("Are you sure you want to log out?", comment: ""), preferredStyle: UIAlertControllerStyle.alert)
    alert.addAction(UIAlertAction(title: "Sign Out", style: UIAlertActionStyle.default, handler: { (alert: UIAlertAction) in

    self.dismiss(animated: true, completion: nil) // CRASH
}))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)

And I want to dismiss my controller with this dialog actions.

So when I click on "Sign Out" button in Alert I get app crashed.

Crash log:

Assertion failure in -[UICollectionViewData validateLayoutInRect:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3698.33.6/UICollectionViewData.m:435 2018-02-23 00:11:17.741531+0300 App[4681:1373962] * Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UICollectionView received layout attributes for a cell with an index path that does not exist: {length = 2, path = 0 - 0}'

BUT! I don't have CollectionView in this controller at all.

NOTE: If I use just a simple self.dismiss(...) without this alert actions, then my controller got dismissed as normal.

NOTE 2: Controller that I want to dismiss is a SplitViewController and I don't have any CollectionViews.

NOTE 3: I present my SplitViewController just in a simple way using self.present(splitVC, animated: true)

Any suggestions?

Upvotes: 0

Views: 356

Answers (1)

atereshkov
atereshkov

Reputation: 4565

The problem was solved.

This crash was caused by layoutAttributesForElements. My cache array wasn't cleared and when layoutAttributesForElements get called crash appears.

If you have a custom CollectionView layout, then you should always clear a cache in prepare() of UICollectionViewLayout.

override func prepare() {
     cache = [UICollectionViewLayoutAttributes]()
     ...
}

So that was the problem.

Upvotes: 0

Related Questions