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.

3
  • 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() instead. It's cleaner and faster. Commented Dec 1, 2011 at 23:36
  • See 'What does your Objective-C singleton look like?' stackoverflow.com/questions/145154/… Commented Dec 1, 2011 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. Commented Dec 1, 2011 at 23:47

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.