我正在尝试初始化一个全局NSMutableArray,我可以在以后添加整数。我只需要知道我应该如何以及在哪里初始化我的数组,以便可以通过我稍后在程序中使用的任何函数来访问和更改它。另外我使用的是Xcode 5,并且知道数组的长度需要为180。
答案 0 :(得分:4)
在AppDelegate.h文件中 -
@property(nonatomic,retain) NSMutableArray *sharedArray;
在AppDelegate.m中
@synthesize sharedArray;
在didFinishLaunchingWithOptions中 -
sharedArray = [[NSMutableArray alloc]init];
现在,
创建AppDelegate的共享对象like-
mainDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
并使用 -
访问您要访问的sharedArraymainDelegate.sharedArray
答案 1 :(得分:4)
您可以创建一个单例类,并为该类的数组定义一个属性。
例如:
// .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
答案 2 :(得分:3)
创建 Singleton 类是更好的选择。在这个单例类中,您可以初始化数组。稍后,您可以使用此单例类从任何类访问此数组。一个很大的好处是你不需要每次都初始化类对象。您可以使用 sharedObject 。
访问该数组以下是目标C中单身人士的教程
答案 3 :(得分:0)
您可以在app delegate的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];
...
}
或者,您可以使用 lazy instantiation :
// 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()
访问数组的全局实例。
但是, 在面向对象编程中被认为是不错的设计实践。想想你的数组是什么,并可能将它存储在管理相关功能的单个对象中,而不是全局存储。