定义全局 NSMutableArray [英] Define global NSMutableArray
问题描述
有没有办法定义一个全局的 NSMutableArray?我希望能够声明数组,以便我可以通过一系列实例方法访问/修改它.这是我下面的代码,我想确保这是我应该做的.
Is there a way to define a global NSMutableArray? I'd like to be able to declare the array so I can access/modify it across a series of instance methods. Here is the code that I have below and want to make sure this is how I should do it.
@interface MainViewController : UIViewController <FlipsideViewControllerDelegate> {
NSMutableArray *sizedWordList;
}
在 .m 中:
sizedWordList = [[NSMutableArray alloc] init];
- (void)dealloc
{
[sizedWordList release];
}
推荐答案
在我看来,您不想要一个全局变量,而是一个实例变量.在这种情况下,您的声明:
It seems to me that you do not want a global variable but, instead, an instance variable. In that case, your declaration:
@interface MainViewController : UIViewController <FlipsideViewControllerDelegate> {
NSMutableArray *sizedWordList;
}
在头文件中是正确的.但是,在实现文件中,您不能在实例方法之外(或者,如果它确实是一个全局变量,则在类方法或函数之外)执行以下操作:
in the header file is correct. However, in the implementation file, you cannot do the following outside of an instance method (or, if it were indeed a global variable, outside of a class method or a function):
sizedWordList = [[NSMutableArray alloc] init];
它在 Objective-C 中是不合法的.初始化实例变量的正确位置是 -init
方法.由于您的类是 UIViewController
的子类,您应该覆盖其指定的初始化程序,-initWithNibName:bundle:
:
It is not legal in Objective-C. The correct place to initialise instance variables is the -init
method. Since your class is a subclass of UIViewController
, you should override its designated initialiser, -initWithNibName:bundle:
:
- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle {
self = [super initWithNibName:nibName bundle:nibBundle];
if (self) {
sizedWordList = [[NSMutableArray alloc] init];
}
return self;
}
你的 -dealloc
方法几乎是正确的——记住你应该总是在你的 末尾发送
方法:[super dealloc]
-dealloc
Your -dealloc
method is almost correct — remember that you should always send [super dealloc]
at the end of your -dealloc
method:
- (void)dealloc
{
[sizedWordList release];
[super dealloc];
}
完成后,您可以在任何其他实例方法中使用该数组.例如,
Having done that, you can use the array in any other instance method. For instance,
- (void)logWordList {
NSLog(@"%@", sizedWordList);
}
这篇关于定义全局 NSMutableArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!