ios - iOS项目初始化项目中需要的所有UIViewController和UIView是不是一个好习惯?

标签 ios objective-c uiview

我看过一个基于角色的iOS项目,作者在应用程序启动时就启动了几乎所有的 View 和 Controller 。并且主要使用NSNotification来进行它们之间的通信。甚至 NSNotification 也是同一种类型,这意味着所有通知都具有相同的名称:

[[NSNotificationCenter defaultCenter] addObserver:aObserver selector:aSelector name:*notification_name* object:nil];
[[NSNotificationCenter defaultCenter] postNotificationName:*notification_name* object:parameter];

它根据不同的notification.object告诉不同类型的通知,它是NSObject的自定义子类,它只包含一些整数,一些字符串和一些对象,如

@interface Parameter : NSObject
{
    // which is an enumeration type to actually define different notification type 
    ParameterID             m_iVCD_ID; 

    int                     m_iInt0;
    int                     m_iInt1;
    int                     m_iInt2;
    float                   m_fFloat0;
    float                   m_fFloat1;
    float                   m_fFloat2;
    NSString                *m_sString0;
    NSString                *m_sString1;
    NSString                *m_sString2;
    NSMutableArray          *m_oArray;

    NSObject                *m_oObject;
    NSObject                *m_oObject0;
    NSObject                *m_oObject1;
    NSObject                *m_oObject2;
}

我觉得这不是一个很好的主意,因为没有对 notification.object 进行类型检查。 基于通知的架构是一个广播系统,因为它对所有通知使用相同的名称。此外,在开始时初始化所有 UIView 和 UIViewController 会消耗大量内存。但是,我没有从控制台看到任何内存警告,而是在使用管理器时在 console.app 中看到。

谁能给一些其他的建议?此架构还有其他不好的方面吗?

最佳答案

我认为这是一个非常非常糟糕的方法。

您评论中的每个论点都是正确的:

I feel that it is not a very good idea because there is no type checking for the notification.object.

当然。

And the notification based architecture is a broadcast system because it uses the same name for all notifications.

除非有意,否则这完全没有意义。

In addition, initializing all UIViews and UIViewControllers at the start cost a lot of memory. However, I haven't seen any memory warning from the console but in console.app when using organizer.

是的,即使没有触发内存警告,它也在浪费内存。 UIViewUIViewController 有自己的生命周期,SDK 为您提供了在需要时加载和卸载(分配和释放)资源的方法。

除此之外, Controller 之间的通信应通过 @property、协议(protocol)或 SDK 提供的任何其他方法来完成。

来自 Apple 文档:

An observer of a given notification may be in a suspended state and not processing notifications immediately.

因此,您不能依赖它们来执行比方说关键任务。

关于ios - iOS项目初始化项目中需要的所有UIViewController和UIView是不是一个好习惯?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23425822/

相关文章:

ios - 在 Objective C 中捕获标准输出

c++ - 如何在 Objective-C 中验证 JSON Schema?

ios - 自定义单元格图像未正确对齐

ios - CGAffineTransform 和 NSLayoutConstraint 冲突

ios - 缩放 CGPath 以适应 UIVIew

ios - iOS NSAttributedString用颜色舍入背景

ios - APNS 通知未到达在 Apple MDM 中注册的设备

objective-c - 自定义 UILabel 不显示文本

ios - 一旦 NSTimer 停止在 objective-c 中关闭我的 View Controller

ios - 在验证方法后未调用 finishedWithAuth