gpt4 book ai didi

objective-c - Objective-C 和 swift

转载 作者:行者123 更新时间:2023-11-28 13:22:01 24 4
gpt4 key购买 nike

我正在尝试将我的一个应用程序从 Objective-C 切换到 swift。 swift 语言中有些东西我无法开始工作。首先,我有一个 Model 类,我在 AppDelegate 的 didFinishLaunchingWithOptions 中对其进行了初始化。我在 Objective-C 的 .h 文件中声明 Model 的对象,如下所示:

@property(nonatomic,retain)Model *model;

didFinishLaunchingWithOptions 中我初始化它:

self.model=[[Model alloc]init];

然后我有以下方法:

+(Model *)getCurrentModel{        
AppDelegate *appdelegate=(AppDelegate *)[UIApplication sharedApplication].delegate;
return appdelegate.model;
}

然后我可以通过调用从任何类访问 Model 的当前实例:

model = [AppDelegate getCurrentModel];

那么,第一个问题,我如何在 Swift 中做同样的事情?尤其是静态函数(以+开头的函数)。我试过这个:

class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
var model : Model?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
// Override point for customization after application launch.
model = Model()
return true
}

class var currentModel : Model {
struct Static {
static let instance : Model = AppDelegate.sharedApplication.delegate //error AppDelegate.Type does not have a member named sharedApplication
}
return Static.instance.model
}

第二个问题。在 Objective C 中,我们可以通过在 .h 文件中声明来生成实例变量、全局变量和全局函数,如下所示:

@interface ViewController : UIViewController {
//Instance Variables
NSString *aName;
}
//Properties or variables that can be accessed globally
NSString *anotherName;

//Methods that have global scope
- (void)doSomething;
@end

那些没有在.h 文件中声明的函数有一个本地作用域。我如何在 Swift 中做同样的事情?

最佳答案

sharedApplicationUIApplication 的方法,而不是 AppDelegate 的方法。此外,您必须解开可选的返回值:

class var currentModel : Model {
struct Static {
static let instance = UIApplication.sharedApplication().delegate as AppDelegate
}
return Static.instance.model!
}

关于objective-c - Objective-C 和 swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24568667/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com