您的位置:首页 > 移动开发 > IOS开发

ios 使用宏创建标准单利

2015-10-22 14:04 645 查看
//
//  Singleton2.h
//  单例的标准写法
//  来自 轩哥

#import <Foundation/Foundation.h>
//使用宏实现单例模板
//    在宏里  \ 表示连接符 宏定义 只能一行

@interface Singleton2 : NSObject
#define DEFINE_SINGLETON_FOR_HEADER(className) \
\
+ (className *)shared##className;

//## 在宏定义表示 连接 宏参数

DEFINE_SINGLETON_FOR_HEADER(Singleton2)
@end


//
//  Singleton2.m
//  单例的标准写法
//<pre name="code" class="objc">//  来自 轩哥
//
//  Singleton2.m
//  单例的标准写法
//
//  Created by LZXuan on 14-8-24.
//  Copyright (c) 2014年 LZXuan. All rights reserved.
//

#import "Singleton2.h"

@implementation Singleton2
#define SYNTHESIZE_SINGLETON_FOR_CLASS(classname) \
\
static classname *shared##classname = nil; \
\
+ (classname *)shared##classname \
{ \
@synchronized(self) \
{ \
if (shared##classname == nil) \
{ \
shared##classname = [[self alloc] init]; \
} \
} \
\
return shared##classname; \
} \
\
+ (id)allocWithZone:(NSZone *)zone \
{ \
@synchronized(self) \
{ \
if (shared##classname == nil) \
{ \
shared##classname = [super allocWithZone:zone]; \
return shared##classname; \
} \
\
} \
\
return nil; \
} \
\
- (id)copyWithZone:(NSZone *)zone \
{ \
return self; \
} \
\
- (id)retain \
{ \
return self; \
} \
\
- (NSUInteger)retainCount \
{ \
return UINT_MAX; \
} \
\
- (oneway void)release \
{ \
} \
\
- (id)autorelease \
{ \
return self; \
}

SYNTHESIZE_SINGLETON_FOR_CLASS(Singleton2)
@end



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: