locoboy
locoboy

Reputation: 38940

Define global 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;
}

In the .m:

sizedWordList = [[NSMutableArray alloc] init];

- (void)dealloc
{
    [sizedWordList release];
}

Upvotes: 1

Views: 6477

Answers (4)

Radu
Radu

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

Sreehari.S
Sreehari.S

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

Nick Weaver
Nick Weaver

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

user557219
user557219

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

Related Questions