码迷,mamicode.com
首页 > 其他好文 > 详细

OC4_单例

时间:2015-06-19 20:16:49      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:

//
//  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;
}

 

OC4_单例

标签:

原文地址:http://www.cnblogs.com/0515offer/p/4589564.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!