Crystal
Crystal

Reputation: 29518

Initialize properties in Singletons in objective-c

So I'm kind of unsure about something. What I want is one class to know about the data through all my different view controllers. This one class should have an array of my objects so that if I have a detailViewController, I would just be looking at one instance in my array that the DataManager would hold. I thought that this DataManager would be a singleton. I followed Apple's documentation on creating a singleton, but now I'm a bit confused on the properties.

static DataManager *sharedDmgr = nil;
+ (id)sharedInstance {
    if (sharedDmgr == nil) {
        sharedDmgr = [[super allocWithZone:NULL] init];
    }
    return sharedDmgr;
}

If I want an NSMutableArray property, what is the proper way to initialize it? Do I do something like

+ (id)sharedInstance {
    if (sharedDmgr == nil) {
        sharedDmgr = [[super allocWithZone:NULL] init];
        [self sharedInit];
    }
    return sharedDmgr;
}

- (void)sharedInit {
      // initialize all my properties for the singleton here?
}

Thanks!

Upvotes: 0

Views: 1116

Answers (2)

danh
danh

Reputation: 62676

You can use the same lazy initialization pattern for your property getters. So for a mutable array...

@interface DataManager ()
@property (strong, nonatomic) NSMutableArray *array;
@end 

@implementation DataManager
@synthesize array=_array;

// shared instance method like @fbernardo's suggestion

- (NSMutableArray *)array {

    if (!_array) {
        _array  = [[NSMutableArray alloc] init];
    }
    return _array;
}

Upvotes: 0

fbernardo
fbernardo

Reputation: 10124

Let's say a DataManager object has a NSMutableArray attribute named "array", then your objective is to be able to do [DataManager sharedDataManager].array in all your code.

The way to do it would be to:

  • Declare the NSMutableArray *array as an attribute on the DataManager.h @interface block.
  • Declare a @property for that attribute.
  • On the - [DataManager init] method initialize the mutable array. Something like self.array = [NSMutableArray array];

Then your sharedInstance method would be:

static DataManager *sharedDmgr = nil;
+ (id)sharedInstance {
    if (sharedDmgr == nil) {
        sharedDmgr = [[DataManager alloc] init];
    }
    return sharedDmgr;
}

All done. Let me know if you need some example code.

Upvotes: 1

Related Questions