//// MySingleton.h// SingleTon//// Created by Realank on 15/8/4.// Copyright (c) 2015年 Realank. All rights reserved.//#import <Foundation/Foundation.h>@interfaceMySingleton : NSObject@property (copy,nonatomic) NSString* string;
+(instancetype) sharedInstance;
// clue for improper use (produces compile time error)
+(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
//// MySingleton.m// SingleTon//// Created by Realank on 15/8/4.// Copyright (c) 2015年 Realank. All rights reserved.//#import "MySingleton.h"@implementationMySingleton
+(instancetype) sharedInstance {
staticdispatch_once_t pred;
staticid shared = nil; //设置成id类型的目的,是为了继承dispatch_once(&pred, ^{
shared = [[super alloc] initUniqueInstance];
});
return shared;
}
-(instancetype) initUniqueInstance {
if (self = [super init]) {
_string = @"hello";
}
returnself;
}
@end
//// main.m// SingleTon//// Created by Realank on 15/8/4.// Copyright (c) 2015年 Realank. All rights reserved.//#import <Foundation/Foundation.h>#import "MySingleton.h"int main(int argc, constchar * argv[]) {
@autoreleasepool {
// insert code here...
MySingleton *sgt = [MySingleton sharedInstance];
NSLog(@"%@",sgt.string);
}
return0;
}