如何在Xcode 6 iOS app中实现main.swift?

TPC*_*PCO 5 xcode ios swift

在我的ios(swift)应用程序中,我创建了main.swift,我在其中设置一个全局变量来检查NSDefault以检查删除的广告.

然后在每个viewcontroller中,我首先检查该全局变量,并在显示视图之前删除广告.

问题是xcode不喜欢AppDelegate.swift中的@UIApplicationMain,因为我有一个main.swift.如果删除@UIApplicationMain行,应用程序会在启动时崩溃.

我实现main.swift错了吗?

Rya*_* H. 10

你的main.swift文件需要看起来像这样:

import Foundation
import UIKit

// Your initialization code here

UIApplicationMain(C_ARGC, C_ARGV, nil, NSStringFromClass(AppDelegate))
Run Code Online (Sandbox Code Playgroud)

UIApplicationMain 将启动事件循环并阻止应用程序退出.

C_ARGC并且C_ARGV是Swift vars,它们代表通过main传递的C参数,即int argcchar *argv[].

更新2016-01-02: C_ARGCC_ARGV已分别替换为Process.argcProcess.unsafeArgv.[ 来源 ]


Har*_*any 7

从问题的很好答案开始,如何在Swift中访问程序参数?来自Darrarski ...

Swift 3语法为:

//
//  main.swift
//

import Foundation
import UIKit

// very first statement after load.. the current time
let WaysStartTime = CFAbsoluteTimeGetCurrent()

// build the parameters for the call to UIApplicationMain()
let argc = CommandLine.argc
let argv = UnsafeMutableRawPointer(CommandLine.unsafeArgv).bindMemory(to: UnsafeMutablePointer<Int8>.self, capacity: Int(CommandLine.argc))

// start the main loop
UIApplicationMain(argc, argv, nil, NSStringFromClass(AppDelegate.self))
Run Code Online (Sandbox Code Playgroud)

并且不要忘记从AppDelegate.swift中删除“ @UIApplicationMain”,因为这将是多余的并导致编译器错误。


Sto*_*yan 5

这就是Swift 5 中的main.swift样子

Hardy_Germany 的回答在 Xcode 10.2 中给出警告。

//
//  main.swift
//  TopLevelCode
//
//  Created by Stoyan Stoyanov on 04/04/2019.
//  Copyright © 2019 Stoyan Stoyanov. All rights reserved.
//

import UIKit
import Foundation

UIApplicationMain(CommandLine.argc, CommandLine.unsafeArgv, nil, NSStringFromClass(AppDelegate.self))
Run Code Online (Sandbox Code Playgroud)

也不要忘记@UIApplicationMain从你的 AppDelegate 中删除标签,在这里阅读更多关于它的信息