views:

68

answers:

1

Here's my singleton code (pretty much boilerplate):

@interface DataManager : NSObject {
    NSMutableArray *eventList;
}

@property (nonatomic, retain) NSMutableArray *eventList;

+(DataManager*)sharedDataManager;

@end

And then the .m:

#import "DataManager.h"

static DataManager *singletonDataManager = nil;

@implementation DataManager

@synthesize eventList;

+(DataManager*)sharedDataManager {
    @synchronized(self) {
        if (!singletonDataManager) {
            singletonDataManager = [[DataManager alloc] init];
        }
    }
    NSLog(@"Pulling a copy of shared manager.");
    return singletonDataManager;
}

So then in my AppDelegate, I load some stuff before launching my first view:

NSMutableArray *eventList = [DataManager sharedDataManager].eventList;

....

NSLog(@"Adding event %@ to eventList", event.title);
[eventList addObject:event];
NSLog(@"eventList now has %d members", [eventList count]);
[event release];

As you can see, I've peppered the code with NSLog love notes to myself. The output to the Log reads like:

2010-05-10 09:08:53.355 MyApp[2037:207] Adding event Woofstock Music Festival to eventList
2010-05-10 09:08:53.355 MyApp[2037:207] eventList now has 0 members
2010-05-10 09:08:53.411 MyApp[2037:207] Adding event Test Event for Staging to eventList
2010-05-10 09:08:53.411 MyApp[2037:207] eventList now has 0 members
2010-05-10 09:08:53.467 MyApp[2037:207] Adding event Montgomery Event to eventList
2010-05-10 09:08:53.467 MyApp[2037:207] eventList now has 0 members
2010-05-10 09:08:53.524 MyApp[2037:207] Adding event Alamance County Event For June to eventList
2010-05-10 09:08:53.524 MyApp[2037:207] eventList now has 0 members

... What gives? I have no errors getting to my eventList NSMutableArray. But I addObject: fails silently?

A: 

I'm guessing that you haven't created an eventList in your init method of the DataManager?

- (id) init {
    if (self = [super init]) {
        eventList = [NSMutableArray alloc] init];
    }
return self;
}
deanWombourne
Okay. That works, but I'm puzzled by it. In no other sort of class do I have to specifically initialize my ivars/properties, I can just charge in there and use them like they already exist. Does this have to do with ownership issues? Or because it's special in that we want to perma-retain it until the OS reclaims us at application shutdown?
Dan Ray
In your other classes I'm guessing you're inheriting from things i.e. UIViewController etc. Apple has done the work to instantiate the ivars for you. You will find yourself doing this all the time as you start to use more custom objects in your code. It's nothing to do with the singleton nature of this.
deanWombourne
And you should also remember to call [eventList release]; in your dealloc method for all ivars/properties declared in your init method or you'll get memroy leaks (this is a singleton so not actually a problem here but it's good practice anyway).
deanWombourne