实例化单例类

Top*_*hef 3 iphone cocoa-touch objective-c

我创建了一个单例类来跟踪我的iPhone应用程序上的数据.我知道singleton只需要实例化一次,但实例化它的最佳位置是什么?应该在appDelegate中完成吗?我希望能够从众多类中调用此单例(包含NSMutableArray),以便我可以访问该数组.

这是我写的课程:

#import "WorkoutManager.h"

static WorkoutManager *workoutManagerInstance;

@implementation WorkoutManager
@synthesize workouts;

+(WorkoutManager*)sharedInstance {
    if(!workoutManagerInstance) {
        workoutManagerInstance = [[WorkoutManager alloc] init];
    }
    return workoutManagerInstance;
}

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

@end
Run Code Online (Sandbox Code Playgroud)

Rob*_*ier 6

在几乎所有情况下,单身人士的观点是你不关心谁首先实例化它.谁是第一个打电话的人[Something sharedSomething]将是创造者.您希望使用" 如何实现与ARC兼容的Objective-C单例? "中给出的模式.它将确保仅创建一次单例.