当前位置

网站首页> 程序设计 > 开源项目 > 程序开发 > 浏览文章

Objective-C 单例宏

作者:小梦 来源: 网络 时间: 2024-08-23 阅读:

实现

先贴出代码
也可以直接访问我的github:RWSingleton

#import <objc/runtime.h>#define RW_DECLARE_SINGLETON_FOR_CLASS_WITH_ACCESSOR(classname, accessorMethodName) \+ (classname *)accessorMethodName;#if __has_feature(objc_arc)    #define RW_SYNTHESIZE_SINGLETON_RETAIN_METHODS#else    #define RW_SYNTHESIZE_SINGLETON_RETAIN_METHODS \    - (id)retain \    { \        return self; \    } \    \    - (NSUInteger)retainCount \    { \        return NSUIntegerMax; \    } \    \    - (oneway void)release \    { \    } \    \    - (id)autorelease \    { \        return self; \    }#endif#define RW_SYNTHESIZE_SINGLETON_FOR_CLASS_WITH_ACCESSOR(classname, accessorMethodName) \\static classname *accessorMethodName##Instance = nil; \\+ (classname *)accessorMethodName \{ \    static dispatch_once_t onceToken;\    dispatch_once(&onceToken,^{\        accessorMethodName##Instance = [super allocWithZone:NULL]; \        accessorMethodName##Instance = [accessorMethodName##Instance init]; \        method_exchangeImplementations(\    class_getInstanceMethod([accessorMethodName##Instance class], @selector(init)),\    class_getInstanceMethod([accessorMethodName##Instance class], @selector(init_once)));\    });\    return accessorMethodName##Instance; \}\\+ (id)allocWithZone:(NSZone *)zone \{ \    return [self accessorMethodName]; \} \\- (id)copyWithZone:(NSZone *)zone \{ \    return self; \} \- (id)init_once\{ \    return self; \} \RW_SYNTHESIZE_SINGLETON_RETAIN_METHODS#define RW_DECLARE_SINGLETON_FOR_CLASS(classname) RW_DECLARE_SINGLETON_FOR_CLASS_WITH_ACCESSOR(classname, shared##classname)#define RW_SYNTHESIZE_SINGLETON_FOR_CLASS(classname) RW_SYNTHESIZE_SINGLETON_FOR_CLASS_WITH_ACCESSOR(classname, shared##classname)

使用

例如你需要一个名为MyOjbect的单例. 在MyOjbect.h中,代码如下:

#import "RWSingletonMacro.h"@interface MyObject : NSObjectRW_DECLARE_SINGLETON_FOR_CLASS_WITH_ACCESSOR(MyObject, sharedObject)@end

MyObject.m中:

#import "MyObject.h"@implementation MyObjectRW_SYNTHESIZE_SINGLETON_FOR_CLASS_WITH_ACCESSOR(MyObject, sharedObject)@end

注意

很多时候,单例都会拥有自己的instance varible,所以这里做了method siwwizling, 你可以重载
-(id)init,在其中实现你的初始化逻辑.MyObject.m看起来如下:

#import "MyObject.h"@implementation MyObjectRW_SYNTHESIZE_SINGLETON_FOR_CLASS_WITH_ACCESSOR(MyObject, sharedObject)- (id) init{  self = [super init];  //do your things  return self}@end

此外,从实现中可得知,即便是如下代码也可以保证obj是单例。

MyObject* obj = [[MyObject alloc] init];

热点阅读

网友最爱