The @UIApplicationMain example in swift is explained in detail

  • 2020-06-07 05:23:08
  • OfStack


Recently, I met some knowledge points that need to be sorted out and recorded in the study of swift. The following article mainly introduces the related contents of @UIApplicationMain in swift and share them for your reference and study. The following words are not enough, let's have a look at the detailed introduction.

How does the program start

In C, the entry point of the program is main function. When the iOS app project of ES12en-ES13en is created, Xcode will give us a file of ES17en.m.

#import <UIKit/UIKit.h>
#import "AppDelegate.h"
int main(int argc, char * argv[])
 @autoreleasepool {
  return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));

We call the UIApplicationMain method of UIKit, which initializes an UIApplication or its subclass object to receive events based on the third argument. The default UIApplication is used when nil is passed in. The last parameter specifies the AppDelegate class as the delegate for the application to receive the delegate methods associated with the application lifecycle.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
- (void)applicationWillResignActive:(UIApplication *)application {
- (void)applicationDidEnterBackground:(UIApplication *)application {
- (void)applicationWillEnterForeground:(UIApplication *)application {
- (void)applicationDidBecomeActive:(UIApplication *)application {
- (void)applicationWillTerminate:(UIApplication *)application {

Although this method indicates that an int is to be returned, it does not actually return an int, but a 1 exists in memory until the user or system applies a forced termination.

Corresponding cases in swift

After creating one swift project, we found that none of the files were similar to the ES40en.m file in ES38en-ES39en, and there were no main functions. The only one related to main is the @UIApplicationMain tag in AppDelegate.

import UIKit
class AppDelegate: UIResponder, UIApplicationDelegate {

The purpose of this tag is to create an UIApplication and start the entire program using the annotated class as a delegate. In general we don't need to make any changes to this tag, but if we want to use a subclass of UIApplication instead of itself, we need to customize an ES51en.swift file (remember to delete the @UIApplicationMain tag). This file we do not need to define the scope, just write the code on OK.

import UIKit
class MyApplication: UIApplication {
 override func sendEvent(_ event: UIEvent) {
  print("Event sent:\(event)")
   to: UnsafeMutablePointer<Int8>.self,
   capacity: Int(CommandLine.argc)),

So that every time we send an event (click a button or something) we can listen to it.


Related articles: