在哪里存储“全球” iOS中的对象 [英] where to store "global" objects in iOS
问题描述
我有一些全局对象(几乎在所有应用程序屏幕中使用),大多数是在应用程序启动后立即创建的。我想从我的所有ViewControllers访问这些对象(没有别的,只有ViewControllers)。在哪里存储?
I have some global object (uses in almost all Application Screens) and mostly they are created right after application starts. I want to have access to this objects from all my ViewControllers (nothing else, only ViewControllers). Where to store it?
我想在 AppDelegate $ c中
@property
$ c>但我认为(但我可能是错的)这是一个丑陋的解决方案。
I think about @property
in AppDelegate
but i think (but I can be wrong) this is a ugly solution.
对象可能非常复杂,这不是一个简单的类型。
Objects can be quite complex, this is not a simple types.
推荐答案
您可以将全局对象放在具有类方法的类中,以访问全局对象,实现 +(void)load
来准备这些对象并存储它们,从而使全局对象可访问在静态变量中。
You can make global objects accessible by placing them in a class with class methods for accessing global objects, implementing +(void)load
to prepare these objects, and storing them in static variables.
标题:
@interface GlobalObjects
+(void)load;
+(MyObject1*)myObject1;
@end
实施:
#import "GlobalObjects.h"
static MyObject1* _myObject1 = nil;
@implementation GlobalObjects
+(void)load {
_myObject1 = [[MyObject1 alloc] init];
}
+(MyObject1*)myObject1 {
return myObject1;
}
@end
用法:
MyObject1 *shared = [GlobalObjects myObject1];
您也可以在其方法中将变量设为静态以进行延迟初始化。
You could also make the variable static inside its method for lazy initialization.
这篇关于在哪里存储“全球” iOS中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!