标签:
// // MusicManager.h // OC4_单例 // // Created by zhangxueming on 15/6/19. // Copyright (c) 2015年 zhangxueming. All rights reserved. // #import <Foundation/Foundation.h> @interface MusicManager : NSObject //单例方法 //通常以 default 或者 shared 开头 + (MusicManager *)defaultMusicManager; @end // // MusicManager.m // OC4_单例 // // Created by zhangxueming on 15/6/19. // Copyright (c) 2015年 zhangxueming. All rights reserved. // #import "MusicManager.h" static MusicManager *music=nil; @implementation MusicManager //方法一: //+ (MusicManager *)defaultMusicManager //{ // if (music==nil) { // music = [[MusicManager alloc] init]; // } // return music; //} //方法二: //+ (MusicManager *)defaultMusicManager //{ // //加线程锁 // @synchronized(self) // { // if (music == nil) { // music = [[MusicManager alloc] init]; // } // } // return music; //} //GCD写法 + (MusicManager *)defaultMusicManager { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ if (music == nil) { music = [[MusicManager alloc] init]; } }); //NSLog(@"onceToken = %li", onceToken); return music; } @end // // main.m // OC4_单例 // // Created by zhangxueming on 15/6/19. // Copyright (c) 2015年 zhangxueming. All rights reserved. // #import <Foundation/Foundation.h> #import "MusicManager.h" //单例类:该类创建的对象有且只有一个 int main(int argc, const char * argv[]) { @autoreleasepool { MusicManager *m1 = [MusicManager defaultMusicManager]; MusicManager *m2 = [MusicManager defaultMusicManager]; MusicManager *m3 = [MusicManager defaultMusicManager]; NSLog(@"m1 = %p m2 = %p m3 = %p", m1,m2, m3); } return 0; }
标签:
原文地址:http://www.cnblogs.com/0515offer/p/4589564.html