Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
+(Singleton *) sharedInstance
{
static Singleton * sharedInstance= nil;
static dispatch_once_t once_token = 0;
dispatch_once(&once_token, ^
{
sharedInstance = [Singleton new];
});
return sharedInstance ;
}
@interface MySingleton : NSObject
+(instancetype) sharedInstance;
// следующие объявления сгенерируют compile time ошибки при попытке их вызвать вручную.
// добавляем -copyWithZone: -allocWithZone: -copy по вкусу
+(instancetype) alloc __attribute__((unavailable("alloc not available, call sharedInstance instead")));
-(instancetype) init __attribute__((unavailable("init not available, call sharedInstance instead")));
+(instancetype) new __attribute__((unavailable("new not available, call sharedInstance instead")));
@end
@implementation MySingleton
+(instancetype) sharedInstance {
static dispatch_once_t pred;
static id shared = nil;
dispatch_once(&pred, ^{
shared = [[super alloc] initUniqueInstance];
});
return shared;
}
-(instancetype) initUniqueInstance {
return [super init];
}
@end
Синглтон (Перевод с английского главы «Singleton» из книги «Pro Objective-C Design Patterns for iOS» Carlo Chung)