实现步骤:
1> 要实现singleton的类中提供一个类方法与外界分享
自己的唯一实例对象
2> 该类的实现文件中,声明一个static(表示该全局变量作用域只能在当前文件中)
的该类全局变量,存放唯一实例
3> 该类中重写那些关于产生新对象或销毁对象的方法,防止产生多个实例
和防止销毁唯一实例(单例对象一般在整个程序退出后才销毁)
- #import <Foundation/Foundation.h>
- @interface MySingleton :NSObject<NSCopying>
- {
- @private
- NSMutableDictionary * _dict;
- }
- // 对外部提供获取唯一实例的类方法
- +(id)shareMySingleton;
- -(NSMutableDictionary *)dict;
- @end
-
-
- int main(int argc, const char * argv[])
- {
- NSAutoreleasePool *pool =[[NSAutoreleasePool alloc] init];
-
- MySingleton *s1=[MySingleton shareMySingleton];
- [[s1 dict] setValue:@"value01" forKey:@"key01"];
-
- //单例对象无论怎么创建都是返回同一个唯一实例,也不会被销毁
- MySingleton *s2=[[MySingleton shareMySingleton] autorelease];
- MySingleton *s3=[[[MySingleton alloc] init] retain];
- MySingleton *s4=[s3 copy];
- [s4 release];
- NSLog(@"\ns1=%@,s2=%@,s3=%@,s4=%@\n%lu,%lu",s1,s2,s3,s4,
- [s4 retainCount],[[s4 dict] retainCount]);
-
- [pool drain];
-
- NSLog(@"\ns1=%@,s2=%@,s3=%@,s4=%@\n%lu,%lu",s1,s2,s3,s4,
- [s4 retainCount],[[s4 dict] retainCount]);
-
- return 0;
- }
- // 全局变量定义为static,限制在本文件中访问
- static MySingleton * _mySingleton = nil;
- @implementation MySingleton
- +(id)shareMySingleton
- {
- // 使用线程锁保证线程安全
- if(!_mySingleton)
- {
- @synchronized(self)
- {
- if(!_mySingleton)
- {
- _mySingleton=[[self alloc] init];
- // 此处应该用alloc创建对象,防止被自动释放池释放
- _mySingleton->_dict=[[NSMutableDictionary alloc] init];
- }
- }
- }
- return _mySingleton;
-
- }
- -(NSString *)description
- {
- return [NSString stringWithFormat:@"%@",_dict];
- }
- -(NSMutableDictionary *)dict
- {
- return _dict;
- }
- // 重写类的创建方法,alloc方法中调用该方法
- +(id)allocWithZone:(NSZone *)zone
- {
- if(!_mySingleton)
- {
- @synchronized(self)
- {
- if(!_mySingleton)
- {
- _mySingleton=[super allocWithZone:zone];
-
- }
- }
- }
- return _mySingleton;
-
- }
- -(id)copyWithZone:(NSZone *)zone
- {
- return self;
- }
- -(id)retain
- {
- return self;
- }
- -(oneway void)release
- {
- }
- -(id)autorelease
- {
- return self;
- }
- -(NSUInteger)retainCount
- {
- return UINT_MAX;
- }
- @end
复制代码
|
|