gpt4 book ai didi

ios - 如何使 iOS Storyboard 中初始化的对象成为单例

转载 作者:行者123 更新时间:2023-11-29 00:44:36 25 4
gpt4 key购买 nike

你能告诉我如何在 iOS Storyboard中初始化单例吗?到目前为止,我的理解是标准模式在我们希望成为单例的类中看起来像这样,并且这段代码有效:

class var sharedInstance: LibraryAPI {
struct Singleton {
static let instance = LibraryAPI()
}
return Singleton.instance
}

相同的模式不适用于 MusicPlayer: enter image description here

我正在制作一个依赖 AVPlayer 来播放音频的自定义 MusicPlayer 对象。我希望这个 MusicPlayer 在 App 被激活后立即存在。目前 MusicPlayer 是在 Storyboard 中创建的,以允许我使用 IBOutlets 和 IBActions 将按钮和标签连接到 MusicPlayer。挑战是当我导航回 viewController 堆栈时 MusicPlayer 被释放。如下图所示。

enter image description here

我可以覆盖哪些方法来查看 Storyboard 何时创建和销毁 MusicPlayer?到目前为止,您可以看到调用了 override init() 但没有调用 deinit。我还没有在文档或网上找到答案。

可能有更好的方法来设计此应用。我认为 Singleton 是有道理的,因为永远应该只有一个 MusicPlayer。只有它的状态会在应用程序的整个生命周期中发生变化。

感谢您的建议。

最佳答案

class var sharedInstance: LibraryAPI {
struct Singleton {
static let instance = LibraryAPI()
}
return Singleton.instance
}

这看起来太复杂了。你通常可以只使用:

final class MusicPlayer {
let sharedInstance = MusicPlayer()
init() {}
}

如果 Something 不是 final,事情确实会变得有点复杂,但通常它可以用于单例。

At present the MusicPlayer is create in the Storyboard to allow me to use IBOutlets and IBActions to connect the buttons and labels to the MusicPlayer.

这行不通。参见 rdar:25450179对于我的问题版本。 Apple 的最新解释是,这可能无法修复。这需要对 Storyboard 进行过多的重新设计。他们可能会改变主意,但这是一个很大的改变。

您最接近的是通过您的类公开单例。

class MyClass: UIViewController {
var musicPlayer: MusicPlayer { return MusicPlayer.sharedInstance() }
}

但这可能也不会做您想要的。通常,您需要将 IBOutlets 直接绑定(bind)到 View Controller 。然后 View Controller 可以根据需要代理到其他对象。

关于ios - 如何使 iOS Storyboard 中初始化的对象成为单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38806110/

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