I want a NSMutableArray global. I have the following setup:

code.h
extern NSMutableArray *global
@interface
@end

code.m
NSMutableArray *global=nil;
@implementation
...
global=variable_mutablearray; //copy variable_mutablearray to global
@end

I'm pretty sure that what I'm doing setting an existing nsmutablearray to the global variable is not correct. What should I be doing?

share|improve this question

60% accept rate
1  
If you are trying to create a truly global object (as opposed to, say, a singleton) in Objective-C you are almost certainly doing something wrong. Can you elaborate on what your goal is? – Conrad Shultz Jul 30 at 3:00
1  
As above, singleton is almost certainly the way to go. Your copy operation is only a shallow copy as well. You are only copying the memory location as opposed to the contents of the array. – danielbeard Jul 30 at 3:02
feedback

2 Answers

up vote 2 down vote accepted

Globals are not the best thing to use in Objective C: it is much better to use a singleton.

You can do it like this:

Header:

@interface Globals
+(NSMutableArray*)array;
@end

Implementation:

@implementation Globals
+(NSMutableArray*)array {
    static NSMutableArray *statArray;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        statArray = [NSMutableArray array];
    });
    return statArray;
}
@end

Usage:

NSMutableArray *ga = [Globals array];
share|improve this answer
1  
Note that this implementation is highly thread unsafe. The preferred approach is to use dispatch_once(), which provides for thread-safety. – Conrad Shultz Jul 30 at 3:08
@ConradShultz You're right, this is the approach that Apple recommends. I changed the implementation, thanks! – dasblinkenlight Jul 30 at 3:14
Much better. :-) – Conrad Shultz Jul 30 at 3:19
feedback

I have to assume the line "global = variable_mutablearray;" is an assignment inside of a method that you call at some point.

This would work but you must keep in mind that the 'ownership' of this object would be questionable at best. Namely every time it is assigned or reassigned the assigner should probably treat the global as if it was an ivar for a class (meaning that you would retain the assignee object, release the global, then assign the assignee to the global). You need to ensure you don't do something like assign with an autoreleased object.

I do agree that a singleton/encapsulating the data some other way would be preferred. But ultimately Objective-C is C and thus inherits the global/shared memory paradigm.

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.