iphone - App delegate 分配的对象显示在多个 subview 中?

标签 iphone ios xcode memory-leaks

我在这里有点纠结.. 构建一个包含两个 View 的 iOS 游戏:BaseView 和 MapView。现在,这些当然有相同的 appDelegate。

它们都使用名为 rivbox 的 UIView 子类。在早期的构建中,我在 Base 和 Map-view 中分配了一个 rivbox 实例。当我意识到我将有很多使用此 rivbox 的 subview 时,我选择在 appDelegate 中分配 just ONE instance of rivbox 然后,当加载 subview 时“借用”通过使用这些漂亮的函数从 appDelegate 中获取 rivbox。

-(void)viewDidLoad {
//Get all the sweets from the parent!
    appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    rivbox = appDelegate.rivbox;
    [self.view addSubview:rivbox];
...
}

如果我们再次返回此 View ,此功能用于更新所有权

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if(rivbox != nil) {
        [rivbox setDelegate:self];
        [self.view addSubview:rivbox];
    }
}

这很好用!我在 appDelegate 中找到了 rivbox,它已经更新了!当我移动到另一个 View 时,它也加载在那里就好了!但是当我回到第一个 View 时,这似乎在泄漏?!?!当我返回之前的 View 时,我在之前的 View 中看不到 rivbox,尽管之前的 View 现在拥有它!

问题是:这有什么问题?每次返回已加载的 View 时,我真的必须将 rivbox 添加为 subview 吗?如果我删除该字符串,那么当我返回到之前的 View 时就看不到 MyBox。

最佳答案

这真是糟糕的做法。如果您在任何类中引用应用程序委托(delegate),您可能需要重新考虑您在做什么。

来自 Apple's docs :

The app delegate is a custom object created at app launch time, usually by the UIApplicationMain function. The primary job of this object is to handle state transitions within the app. For example, this object is responsible for launch-time initialization and handling transitions to and from the background.

为其他任何事情引用 App Delegate 就像使用全局变量一样。一开始这似乎是一条简单的捷径,但随着代码库的增长,很快就会变得一团糟。

app delegate 就是它所说的 - UIApplication 的委托(delegate)对象。您正在创建的 View 与 UIApplication 无关,因此不应靠近它的委托(delegate)。

设计和构建简单、独立的类,鼓励重复使用。从长远来看,您会很高兴自己做到了。

您认为创建这个单一的 rivbox 有什么优势?

关于iphone - App delegate 分配的对象显示在多个 subview 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8729698/

相关文章:

iphone - 更改项目名称后,产品 iOS 需要代码签名

ios - 无法创建新的客户端 ID(适用于 iOS SDK 中的 google plus 登录)

ios - Facebook iOS SDK 4.1.0 分享回调

ios - 页面 View Controller 出错

c++ - 带有 C 接口(interface)的 Objective C 库

iphone - 如何在单个 View Controller 中创建两个多个 UIPickerview

ios - 将 NSString 转换为 int16_t 并将它们插入到核心数据中

ios - 在 SpriteKit 中出现错误。 - 线程 1 : EXC_BREAKPOINT (code=1, 子代码 = 0x1007351fc)

ios - 如何在 Swift 中实现 MVC?

ios - Swift 包管理器 - 在包的 Storyboard中设置自定义类失败