Reputation: 38940
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;
}
In the .m:
sizedWordList = [[NSMutableArray alloc] init];
- (void)dealloc
{
[sizedWordList release];
}
Upvotes: 1
Views: 6477
Reputation: 3494
Sure you can create a class and import it where you want to use it.
header:
#import <Foundation/Foundation.h>
extern NSMutableArray * typesArray;
@interface GlobalVariables : NSObject {
}
@end
implementation
#import "GlobalVariables.h"
@implementation GlobalVariables
NSMutableArray * typesArray;
@end
Now you have acces to typesArray anywheare you import the header
Upvotes: 0
Reputation: 1
Create a singleton instance of the array in your AppDelegate and access it across your application.
**YourAppDelegate *delegate = (YourAppDelegate *) [[UIApplication sharedApplication] delegate];**
'delegate.sizedWordList' is your global array
Try it out. Good luck.
Upvotes: 0
Reputation: 47241
You can create a singleton and share the instance. A singleton will allow only one existing instance of a class to exist. So every accessing code uses the same instance.
Upvotes: 0
Reputation:
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];
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;
}
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);
}
Upvotes: 1