gpt4 book ai didi

ios - [UIApplication sharedApplication].delegate 的转换

转载 作者:行者123 更新时间:2023-11-29 03:38:47 26 4
gpt4 key购买 nike

我有一个测试项目可以在多个 View Controller 上使用私有(private)数据对象。(我是从网络和 git-hub 下载的)

- (ExampleAppDataObject*) theAppDataObject;
{
id<AppDelegateProtocol> theDelegate = (id<AppDelegateProtocol>) [UIApplication sharedApplication].delegate;
ExampleAppDataObject* theDataObject;
theDataObject = (ExampleAppDataObject*) theDelegate.theAppDataObject;
return theDataObject;
}

第一个问题是,delegate 是用 AppDelegateProtocol 转换的,即使这个应用程序 UIApplication 委托(delegate)名称是 ViewControllerDataSharingAppDelegate,也没有警告。我不明白为什么,也许是因为那是一个 id 类型?(AppDelegateProtocol是他在AppDelegate中声明的自定义委托(delegate)协议(protocol)。)

其次,它在每个 View Controller 上都显示了这种代码,它看起来只是一个单一模式。我不认为这不是在 View Controller 之间传输数据的最佳方式。哪种是传输对象数据类型的最佳方式?

谢谢。

最佳答案

创建协议(protocol)会在某种程度上将代码与具体实现分离。您可以想象有多个应用程序,每个应用程序都使用自己的自定义类作为应用程序委托(delegate),但所有实现都符合 AppDelegateProtocol。

当我刚开始使用 iOS 时,我经常使用应用委托(delegate)来保存全局数据和方法。

但是,这会用特定于应用的代码填充您的应用委托(delegate)。

我最近放弃了这种方法,并使用数据容器单例(也许还有实用程序方法单例)。与单例的典型情况一样,我定义了一个类方法来获取单例。我根据需要向我的单例添加属性以存储数据,然后只需使用类方法获取指向单例的指针。我编写类方法来延迟加载单例。

通过使其符合 NSCoding,也很容易使您的数据容器单例持久化。然后每次你被转移到后台时,只需将你的单例保存在某个地方。在应用程序启动时,读入它。

关于ios - [UIApplication sharedApplication].delegate 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18771889/

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