如何以及在哪里初始化Xcode 5中的全局NSMutableArray

我想初始化一个全局的NSMutableArray,我可以稍后添加整数。 我只需要知道如何和在哪里我应该初始化我的数组,以便它可以被我在程序中稍后使用的任何函数访问和更改。 此外,我正在使用Xcode 5,并知道数组需要是180的长度。

在你的AppDelegate.h文件中 –

@property(nonatomic,retain) NSMutableArray *sharedArray; 

在AppDelegate.m中

 @synthesize sharedArray; 

在didFinishLaunchingWithOptions中 –

 sharedArray = [[NSMutableArray alloc]init]; 

现在,

使创build像AppDelegate的共享对象,

 mainDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate]; 

并访问共享arrays你想访问使用 –

 mainDelegate.sharedArray 

您可以创build一个单例类,并为该类的数组定义一个属性。

例如:

 // .h file @interface SingletonClass : NSObject @property (nonatomic,retain) NSMutableArray *yourArray; +(SingletonClass*) sharedInstance; @end // .m file @implementation SingletonClass +(SingletonClass*) sharedInstance{ static SingletonClass* _shared = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _shared = [[self alloc] init]; _shared.yourArray = [[NSMutableArray alloc] init]; }); return _shared; } @end 

创build一个Singleton类对你来说是更好的select。 在这个单例类中,你可以初始化数组。 稍后,您可以使用此单例类从任何类访问此数组。 一个很大的好处是你不需要每次初始化类对象。 您可以使用sharedObject访问数组。

以下是目标C中的单例教程

http://www.galloway.me.uk/tutorials/singleton-classes/

您可以在应用程序委托的application:didFinishLaunchingWithOptions:初始化您的数组application:didFinishLaunchingWithOptions:方法,因为在启动应用程序后立即调用它:

 // In a global header somewhere static NSMutableArray *GlobalArray = nil; // In MyAppDelegate.m - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { GlobalArray = [NSMutableArray arrayWithCapacity:180]; ... } 

另外 ,你可以使用懒惰的实例

 // In a global header somewhere NSMutableArray * MyGlobalArray (void); // In an implementation file somewhere NSMutableArray * MyGlobalArray (void) { static NSMutableArray *array = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ array = [NSMutableArray arrayWithCapacity:180]; }); return array; } 

然后可以使用MyGlobalArray()来访问数组的全局实例。

但是,这在面向对象编程中并不被认为是很好的devise实践 。 考虑一下你的数组是什么,并且可能把它存储在pipe理相关function的单例对象中,而不是全局地存储它。