Home > Back-end >  Swift - Does not reloadData work in sequence?
Swift - Does not reloadData work in sequence?

Time:10-03

i think the code in Xcode works in sequence.
for example

print("1")
print("2")
print("3")

// result
// 1
// 2
// 3

but when i call reloadData, it does not work in sequence.

{
   ...
   collectionView.reloadData()
   print("1")
   print("2")
   ...
}

after called reloadData, print("1"), ("2") works.
and later, collectionView's dataSource method is called.

i think reloadData includes DataSource's methods and Delegate's methods.
so, i think,
after called reloadData, dataSource's methods is called, and the print("1"), ("2").

why reloadData does not work in sequence?
i didn't make any dispatchQueue.

CodePudding user response:

It's because of the way the run loop works. Your code runs within an implicit transaction. Your code comes to an end, and then the transaction commits itself. It is then, as part of the transaction commit procedure, that the screen is updated: first layout, then drawing, then obedience to layer property changes, then the start of any animations.

So basically reloadData is a request to queue up redrawing of the table view, but the actual redrawing doesn't take place until all your code has stopped and the transaction is committed.

(It might help to think of this as parallel to setNeedsDisplay.)

  • Related