tags:

views:

48

answers:

3

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.

+1  A: 

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.

Nicolas Goy
As per what zoul said, I documented how to do it, now I agree with zoul, using global variable is hardly even a good design, and if you don't have good reasons, don't do it.
Nicolas Goy
A: 

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.

zoul
A: 

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.

spbfox