Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
750 views
in Technique[技术] by (71.8m points)

objective c - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...