标签:
.h文件
#import <Foundation/Foundation.h> @interface HMMusicTool : NSObject <NSCopying> @property (nonatomic, strong) NSMutableArray *musics; + (instancetype)shareTool; @end
.m文件
#import "HMMusicTool.h" @interface HMMusicTool () @end; @implementation HMMusicTool // 全局变量 // 用static修饰,能够保证_musicTool只能够被当前文件(.m)访问,其它外部文件不能访问 static id _musicTool; - (NSMutableArray *)musics { if(!_musics) { _musics = [NSMutableArray array]; } return _musics; } // alloc方法内部调用这个方法 + (instancetype)allocWithZone:(struct _NSZone *)zone { if(!_musicTool){ // 防止频繁加锁 // 加锁,线程安全 @synchronized(self){ // 防止创建多次 if(!_musicTool){ _musicTool = [super allocWithZone:zone]; } } } return _musicTool; } + (instancetype)shareTool { if(!_musicTool){ // 防止频繁加锁 @synchronized(self){ if(!_musicTool) // 防止创建多次 { _musicTool = [[self alloc] init]; } } } return _musicTool; } - (id)copyWithZone:(NSZone *)zone { return _musicTool; } @end
标签:
原文地址:http://www.cnblogs.com/fkunlam/p/4342345.html