0

I want to build a shared object that all the classes will be able to access to it. i want that in this object will be NSMutableArray .

this is how i call this object

+(id)sharedManager{
@synchronized(self) {
    if (sharedManager == nil){
        sharedManager = [[self alloc] init];
        array = [[NSMutableArray alloc] init];
    }
}
return sharedManager;

}

and this is how i define the NSMutableArray :

@property (nonatomic,retain) NSMutableArray *array;

the problem is that after i create this NSMutableArray in the sharedManager method, every time i try to access the array is equal to Nil.

YosiFZ
  • 7,792
  • 21
  • 114
  • 221
  • With GCD, there's no need for a `@synchronized` block to protect an action that should only occur once. Replace that with a call to [`dispatch_once()`](http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/dispatch_once.3.html) instead. It's cleaner and faster. – Lily Ballard Dec 01 '11 at 23:36
  • See 'What does your Objective-C singleton look like?' http://stackoverflow.com/questions/145154/what-does-your-objective-c-singleton-look-like – Jacob Jennings Dec 01 '11 at 23:45
  • Where is `array` declared? They way you're doing it it has to be declared static, and would not be accessible from a property. You can make the property `readonly` and write your own `getArray` method rather than using `@synthesize`, however, to make it accessible from the property. – Hot Licks Dec 01 '11 at 23:47

1 Answers1

3

You're attempting to set an instance variable from a class method. Instead, you should create array in your -init method in the singleton. That way when you message, sharedManager = [[self alloc] init];, the array will be configured for that shared instance.

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

    if (!self)
        return nil;

    array = [[NSMutableArray alloc] init];

    return self;
}
Mark Adams
  • 30,776
  • 11
  • 77
  • 77