如下所示:
//下面这段宏考过去直接用 #define SYNTHESIZE_SINGLETON_FOR_HEADER(className) \ \ + (className *)sharedInstance;\ + (void)destroyInstance; //在单例生成之前onceToken = 0,在单例生成之后onceToken = -1了,之后一直保持-1这个值,知道这个之后我想你应该有思路了 #define SYNTHESIZE_SINGLETON_FOR_CLASS(className) \ \ static className *shared##className = nil; \ static dispatch_once_t onceToken;\ + (className *)sharedInstance\ {\ return [[self alloc] init];\ }\ + (className *)allocWithZone:(struct _NSZone *)zone\ {\ dispatch_once(&onceToken, ^{\ shared##className = [super allocWithZone:zone];\ });\ return shared##className;\ }\ - (className *)copyWithZone:(NSZone *)zone\ {\ return shared##className;\ }\ - (className *)mutableCopyWithZone:(NSZone *)zone\ {\ return shared##className;\ }\ + (void)destroyInstance {\ shared##className = nil;\ onceToken = 0;\ }\
//用法,注意要遵循NSCopying,NSMutableCopying 协议 import <Foundation/Foundation.h> @interface YNHTUserModel : NSObject<NSCopying,NSMutableCopying> SYNTHESIZE_SINGLETON_FOR_HEADER(YNHTUserModel); @property (nonatomic,copy) NSString* inviter_id;//邀请人ID @property (nonatomic,copy) NSString* token; @property (nonatomic,copy) NSString* nick_name; @end
#import "YNHTUserModel.h" @implementation YNHTUserModel SYNTHESIZE_SINGLETON_FOR_CLASS(YNHTUserModel); @end
以上这篇ios 单利的完整使用实例 及销毁 宏定义就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持呐喊教程。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。