Alex Stelea
Alex Stelea

Reputation: 1219

Global array question

I've tried making a global array that can add and remove items across all view controllers. I've used the App delegate *app .... Method and then allocated an array like this app. Mutable array = nsmutable array alloc init However I can't get it to be implemented globally.

Upvotes: 0

Views: 200

Answers (3)

spbfox
spbfox

Reputation: 949

Actually the singleton is already there. In you current implementation you can use sharedApplication to get your app delegate and access your array through it.

Upvotes: 0

zoul
zoul

Reputation: 104065

Most probably you don’t really need the array to be global, you are just being lazy to design the code properly. Singleton will work, but it only makes the design a step uglier (= harder to work with). The proper solution is to get rid of the global variable. It’s harder, but it will pay off in the long term.

Upvotes: 0

Nicolas Goy
Nicolas Goy

Reputation: 1430

What you need is a static variable and a mean to access it. In Objc, the usual way to do that is with a singleton.

.h file

@interface MySingleton : NSObject {
    NSMutableArray *theArray;
}

+ (MySingleton*)sharedInstance;

@property (readonly) NSMutableArray *theArray;

@end

.m file

@implementation MySingleton

@synthethize theArray;

- (id)init {
    ...
    theArray = [NSMutableArray new];
    ...
}

- (void)dealloc {
    [theArray release];
}
+ (MySingleton*)sharedInstance {
    static MySingleton *s;
    if(!s) s = [[MySingleton alloc] init];
    return s;
}
@end

Then you access your array with:

[MySingleton sharedInstance].theArray

You may also go the C route with something like this, in any .m file put:

NSMutableArray *mySharedArray(void) {
    static NSMutableArray *a;
    if(!a) a = [NSMutableArray new];
    return a;
}

And in any .h file:

NSMutableArray *mySharedArray(void);

Then you can just call mySharedArray() from any code that includes the .h file where it's declared.

NOTE: Either those approach are not thread safe, if you want a thread safe global array, you will have to do some locking.

Upvotes: 1

Related Questions