-
[iOS] ํ์ ์๋ฆผ์ฐฝ ๊ตฌํ ์ค ๋ฐ์ํ Cannot be called with asCopy = NO on non-main thread. ๋ฌธ์ ํด๊ฒฐiOS 2022. 7. 7. 01:21
๋๋ ์๋ ๋ณดํต ํ์ ์๋ฆผ์ฐฝ์ ๋ค์๊ณผ ๊ฐ์ด UIViewController์ extension์ผ๋ก ๋ง๋ค์ด์ ์ฌ์ฉํ๊ณค ํ๋ค.
import UIKit extension UIViewController { func alert(title: String = "์๋ฆผ", message: String, okTitle: String = "ํ์ธ", handler: ((UIAlertAction) -> Void)? = nil) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) let okAction = UIAlertAction(title: okTitle, style: .default, handler: handler) alert.addAction(okAction) present(alert, animated: true, completion: nil) } }์์ ์ ํ๋ค๋ณด๋ ๋ฐฑ๊ทธ๋ผ์ด๋ ์ค๋ ๋์์ ์ด ํ์ ์ฐฝ์ ๋์์ผํ๋ ๊ฒฝ์ฐ๊ฐ ์๊ฒผ๋ค.
๋ฐฑ๊ทธ๋ผ์ด๋์์ ๊ทธ๋ฅ ์ด alert ๋ฉ์๋๋ฅผ ์คํํ๋ ์ด๋ฐ ์ค๋ฅ๊ฐ ๋ฐ์ํ๋ค.

Thread 7: "Modifications to the layout engine must not be performed from a background thread after it has been accessed from the main thread.”
๋น์ฐํ, ๋ฐฑ๊ทธ๋ผ์ด๋ ์ค๋ ๋์์ ๋ ์ด์์์ ๋ณ๊ฒฝํ๋ ์์ ์ ํ๋ฉด ์๋๋ค๋ ๊ฒ์ด๋ค.
๊ทธ๋์ ๋๋ present ๋ฉ์๋๋ฅผ ๋ฉ์ธ ์ค๋ ๋์์ ์คํํ๋๋ก ๋ค์๊ณผ ๊ฐ์ด ๋ณ๊ฒฝํ๋ค.
DispatchQueue.main.async { self.present(alert, animated: true, completion: nil) }์คํํ๋ ์ ์์ ์ผ๋ก ์๋ฆผ์ฐฝ์ด ๋จ๊ณ ํฌ๋์๋ ๋ฐ์ํ์ง ์์์ง๋ง, ์ฝ์์ ์ด๋ฐ ๋ก๊ทธ๊ฐ ์ถ๋ ฅ๋์๋ค.

[Assert] Cannot be called with asCopy = NO on non-main thread.
์ด๊ฒ ๋ญ๊ฐ ์ถ์ด์ ๊ตฌ๊ธ๋ง์ ํ๋ ๋๊ฐ์ ์ง๋ฌธ์ ๋ฐ๊ฒฌ!
DispatchQueue : Cannot be called with asCopy = NO on non-main thread
I am presenting the UIAlertController on the main thread as : class HelperMethodClass: NSObject { class func showAlertMessage(message:String, viewController: UIViewController) { let
stackoverflow.com
present ๋๋ ๋ถ๋ถ๋ง ๋ฉ์ธ ์ค๋ ๋์์ ์คํํ ๊ฒ์ด ์๋๋ผ alert ๋ฉ์๋ ์ ์ฒด๋ฅผ main ์ค๋ ๋์์ ์คํํด์ผํ๋ค๊ณ ์ฝ๋ฉํธ๊ฐ ๋ฌ๋ ค์์๋ค.
์ alert ๋ฉ์๋ ์ ์ฒด๋ฅผ main์์ ์คํํด์ผํ๋์ง ์ดํด๊ฐ ์ ๊ฐ๋๋ฐ, ๋ง์นจ ๋์ ๋น์ทํ ์๋ฌธ์ ์ ๊ฐ์ง์ ๋ถ์ ์ฝ๋ฉํธ๊ฐ ์์๋ค.

UIAlertContoller๊ฐ ๋ฉ์ธ ์ค๋ ๋์์ ์ธ์คํด์คํ๋์ด์ผํ๋ค๊ณ ํ๋ค.
์ค์ ๋ก
Thread.isMainThread๋ฅผ ์ด์ฉํ์ฌ ๋ก๊ทธ๋ฅผ ์ฐ์ด ํ์ธํด๋ณด๋,alert ๋ฉ์๋๋ ์ ์ด์
๋ฐฑ๊ทธ๋ผ์ด๋ ์ค๋ ๋์์ ํธ์ถ์ด ๋๊ณ ์๊ธฐ ๋๋ฌธ์ alert ๋ฉ์๋ ์์ฒด๋๋ฐฑ๊ทธ๋ผ์ด๋ ์ค๋ ๋์์ ์คํ์ด ๋๊ณ ์์๊ณ , present ๋๋ ๋ถ๋ถ๋ง๋ฉ์ธ ์ค๋ ๋์์ ์คํ์ด ๋๊ณ ์์๋ค.๊ทธ๋ ๋ค๋ฉด, ์ UIAlertController๊ฐ ๋ฉ์ธ ์ค๋ ๋์์ ์ธ์คํด์คํ๋์ด์ผํ๋๊ฐ?!
๋ชจ๋ ๋ทฐ์ปจํธ๋กค๋ฌ๋ ๋ฉ์ธ ์ค๋ ๋์์ ์ธ์คํด์คํ๋์ด์ผํ๊ธฐ ๋๋ฌธ์ UIAlertController ๋ํ ๋ฉ์ธ ์ค๋ ๋์์ ์ธ์คํด์คํ๋์ด์ผ ํ๋ค๊ณ ํ๋ค. ๋ทฐ์ปจํธ๋กค๋ฌ๋ ์ธ์ ๋ ์ง ๋ฉ์๋๋ฅผ ํตํด ๋ทฐ๋ฅผ ๋ก๋ํ๊ฑฐ๋ ์์ ํ ์ ์์ด์ผ ํ๊ธฐ ๋๋ฌธ์, UIViewController๋ฅผ ์์ํ๋ UIAlertController ๋ํ ๋ฉ์ธ ์ค๋ ๋์์ ์ธ์คํด์คํ๋์ด์ผํ๋ค๋ ๊ฒ์ด๋ค.
๊ทธ๋์ ์ด alert ๋ฉ์๋๋ฅผ ๋ฉ์ธ ์ค๋ ๋์์ ํธ์ถํ๋ ๊ฒ์ผ๋ก ๋ฌธ์ ํด๊ฒฐ ์๋ฃ~!
DispatchQueue.main.async { self.alert(message: "๊ถํ์ด ์ค์ ๋์ง ์์์ต๋๋ค.") }๊ทผ๋ฐ ๋ฌธ์ ๋ ํด๊ฒฐํ์ง๋ง,,,! with asCopy = NO ๋ผ๋ ๋ฉ์์ง๊ฐ ์ดํด๊ฐ ๊ฐ์ง ์๋๋ฐ ๋ฌด์จ ๋ง์ผ๊น..? ์ฐพ์๋ด๋ ์ ๋์ค๋๋ฐ ์ด๊ฑด ๋ ์์๋ด์ผ๊ฒ ๋ค..
'iOS' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[iOS] Sharing Framework? (0) 2023.02.03 [iOS] Command CompileSwiftSources failed with a nonzero exit code ์ค๋ฅ ํด๊ฒฐ (0) 2022.07.08 [iOS] Coordinator Design Pattern ๋ฒ์ญ (1) 2022.05.26 [iOS] safeAreaLayoutGuide (0) 2022.05.26 [iOS] SwiftLint ์ ์ฉํ๊ธฐ (0) 2022.05.10