两种单例模式的写法

不使用GCD

#import "ServiceManager.h"

static ServiceManager *defaultManager;

@implementation ServiceManager

+(ServiceManager *)defaultManager{
    if(!defaultManager)
        defaultManager=[[self allocWithZone:NULL] init];
    return  defaultManager;
}

@end

使用GCD

#import "ServiceManager.h"
@implementation ServiceManager
+(ServiceManager *)sharedManager{
  static dispatch_once_t predicate;
  static ServiceManager * sharedManager;
  dispatch_once(&predicate, ^{
    sharedManager=[[ServiceManager alloc] init];
  });
  return sharedManager;
}
@end

dispatch_once这个函数,    它可以保证整个应用程序生命周期中某段代码只被执行一次!

posted @ 2015-08-27 18:59  apple家园  阅读(124)  评论(0编辑  收藏  举报