Principal
Why doesn't the current code with an infinite for loop in main work? How to fix it?
sobes.tech AI
Answer from AI
If the main function of an iOS application contains an infinite for loop, the app does not work because the main thread is blocked by this loop and cannot process UI events and system messages.
In iOS, the main event loop (run loop) is managed by the system, and blocking the main thread causes the interface to freeze.
To fix this, you should remove the infinite loop from main and let the system manage the event loop. If you need to perform repetitive tasks, it's better to use timers (Timer), background queues (DispatchQueue), or other asynchronous mechanisms.
Example of incorrect code:
func main() {
for { // infinite loop
// do something
}
}
Correct approach:
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
// periodic task
}
return true
}
}
Thus, do not block the main thread and use system mechanisms for repetitive actions.