单例是一种重要的概念,它是一种极其便利的设计模式
#import <Foundation/Foundation.h>
@interface DanLi : NSObject
{
NSString *someProperty;
}
@property (nonatomic,retain) NSString *someProperty;
+ (id)sharedDanli;
@end
#import "DanLi.h"
@implementation DanLi
@synthesize someProperty;
+ (id)sharedDanli
{
static DanLi *myDanli = nil;
/*通过GCD的dispath_once方法,我们确保sharedMyManager方法只会被创建一次。这是线程安全的,你无需担心什么。*/
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
myDanli = [[self alloc] init];
});
return myDanli;
}
/*不想用GCG,也可以这样实现sharedManager方法:
非-GCD 代码
+ (id)sharedDanli {
@synchronized(self) {
if (myDanli == nil)
sharedMyManager = [[self alloc] init];
}
returnsharedMyManager;
}*/
// 这样来使用单例 MyManager *sharedManager = [MyManager sharedManager];
- (id)init
{
if (self = [super init]) {
someProperty =@"Default Property Value";
}
returnself;
}
-(void)dealloc {
// Should never be called, but justhere for clarity really.
}
@end