使用数据管理单例

时间:2010-05-10 13:19:51

标签: iphone objective-c singleton

这是我的单例代码(几乎是样板文件):

@interface DataManager : NSObject {
    NSMutableArray *eventList;
}

@property (nonatomic, retain) NSMutableArray *eventList;

+(DataManager*)sharedDataManager;

@end

然后是.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;
}

然后在我的AppDelegate中,我在启动第一个视图之前加载了一些东西:

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

正如你所看到的,我已经用自己的NSLog爱情笔记填写了代码。日志的输出如下:

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

......是什么给出的?我没有错误到我的eventList NSMutableArray。但是我addObject:默默地失败了?

1 个答案:

答案 0 :(得分:0)

我猜你还没有在DataManager的init方法中创建一个eventList?

- (id) init {
    if (self = [super init]) {
        eventList = [NSMutableArray alloc] init];
    }
return self;
}