-
네트워크 비동기와 reloadData의 중요성iOS/iOS개념정리 2023. 2. 5. 14:15
계속 고민했던 문제.. 삽질 엄청 했으니 기록
네트워크 작업인 getDocument에서 return 한 개수를 UICollectionView delegtate인 numberOfItemsInSection에서 어떻게 쓰나?
명쾌함. delegate는 UIViewController가 생성되자 마자 호출되나, 그 시점에는 count = nil 임. getDocument는 비동기이므로 실행되고 response를 얻는데 시간이 걸림.. getDoc에서 array에 추가해 주고… 동시에 reloadData를 호출해주면 됨
** Remember, the numberOfItemsInSection delegate method is called right when the view controller is loaded, so putting an async method in there is useless because it takes time to call Firestore and get a response.
예시코드) 매우 좋은 글
https://firebase.blog/posts/2018/07/swift-closures-and-firebase-handling
*** 추가
numberOfItemsInSection 메소드에서 collectionView.reloadData를 호출할 경우
무한 늪에 빠짐.. numberOfItemsInSection 호출 -> collectionView.reloadData -> numberOfItemsInSection 호출 -> collectionView.reloadData -> …..
firebase 네트워크 호출 메소드가 한번만 시행될 경우에는 크게 문제는 없음..
Cell 개수 받아오고, 계속 reload를 해주어도 cell개수에는 변함이 없기 때문에..
다만, 메소드를 for문으로 여러번 호출해야 하는 경우에는
reload늪에 삐져서 cell개수가 무한정 더해지게 됨..
따라서, reloadData를 numberOfItemsInSection에서 호출하는건 바람직하지 않음
viewDidLoad나 view의 init에서 호출해서 한번만 reload 되게끔 해야 cell개수가 한번만 더해지고 끝나게 된다
'iOS > iOS개념정리' 카테고리의 다른 글
[개념정리] RxSwift, Combine (0) 2025.01.10 [개념정리] iOS 전반 (면접대비) (0) 2025.01.10 Completion Handler / Closure (0) 2022.05.15 Timer class vs. GCD DispatchSourceTimer (0) 2022.05.08 [iOS] Delegate, Notification, KVO 비교 및 장단점 정리 (0) 2022.04.20