Search code examples
objective-ciosios4

Global variable NSMuteableArray using Singleton Class


I'm having trouble creating a nice way of passing a collection around to different view controllers. For example, I created a custom class called Message with a bunch of attributes. I want to have a global NSMutableArray of those stored in a global variable of sorts called messages that I can add to or get from anywhere. Everyone on Stackoverflow says not to use your delagate class to store global variables so I created a singleton class called Shared. In there I created a property for the NSMutableArray called messages like this:


@interface Shared : NSObject {

}

@property (nonatomic, retain) NSMutableArray *messages;

+(Shared *) sharedInstance;

@end

And my .h file is (the important part):


#import "Shared.h"
static Shared* sharedInstance;

@implementation Shared

@synthesize messages;

static Shared *sharedInstance = nil;

-(id) init {
    self = [super init];
    if (self != nil){

    }
    return self;
}

-(void) initializeSharedInstance {

}

+ (Shared *) sharedInstance{
    @synchronized(self) {
        if (sharedInstance == nil){
            sharedInstance = [[self alloc] init];
            [sharedInstance initializeSharedInstance];

        }
        return (sharedInstance);
    }
}

In my other view controller, I first import "Shared.h", then try this:


[[Shared sharedInstance].messages addObject:m];

NSLog([NSString stringWithFormat:@"Shared messages = %@", [Shared sharedInstance].messages]);

It keeps printing null instead of the the collection of m objects. Any thoughts?


Solution

  • You need to have a static variable.

    In .h:

    @interface Shared : NSObject
    {
        NSMutableArray *messages;
    }
    
    @property (nonatomic, retain) NSMutableArray *messages;
    
    + (Shared*)sharedInstance;
    
    @end
    

    in .m:

    static Shared* sharedInstance;
    
    @implementation Shared
    
    @synthesize messages;
    
    
    + (Shared*)sharedInstance
    {
        if ( !sharedInstance)
        {
            sharedInstance = [[Shared alloc] init];
    
        }
        return sharedInstance;
    }
    
    - (id)init
    {
        self = [super init];
        if ( self )
        {
            messages = [[NSMutableArray alloc] init];
        }
        return self;
    }