mugetsu
mugetsu

Reputation: 4398

setting NSMutableArray Global variable

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?

Upvotes: 2

Views: 2128

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

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 : NSObject
+(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];

Upvotes: 3

Jared Kipe
Jared Kipe

Reputation: 1187

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.

Upvotes: 0

Related Questions