您的位置:首页 > 理论基础 > 计算机网络

第02天多线程网络:(07):MRC环境下实现单例模式

2017-04-18 00:00 176 查看
#####一、MRC环境下实现单例模式
1.修改项目 为MRC -->project ->target -> buildSettings -> Objective C Automatic Reference Counting -> 设置为NO
2.对实例化的对象进行release、retain、retainCount进行MRC的处理
#####二、MRC模式下的 单例模型处理1.使用条件编译进行处理,判断该项目是不是arc项目
#if#else#endif
#if __has_feature(objc_arc)NSLog(@"ARC");#elseNSLog(@"MRC");#endif
- 2.MRC的单例模式处理
#if __has_feature(objc_arc)// 条件满足 ARC#else// 否则#pragma MRC模式 存储单例模式#pragma mark 1. 重写release方法(oneway void)release{}#pragma mark 2. 重写retain方法(instancetype)retain{return _instance;}#pragma mark 3. 重写retainCount方法// 习惯 (一般返回最大值 : MAXFLOAT)(NSUInteger)retainCount{return MAXFLOAT;}
---
code
LYHTool
.h#import <Foundation/Foundation.h>@interface LYHTool : NSObject+(instancetype)shareTool;@end.m// 修改项目 为MRC -->project ->target -> buildSettings -> Objective C Automatic Reference Counting -> 设置为NO//#import "LYHTool.h"@implementation LYHToolstatic LYHTool *_instance;+(instancetype)allocWithZone:(struct _NSZone *)zone{static dispatch_once_t onceToken;dispatch_once(&onceToken, ^{_instance = [super allocWithZone:zone];});
return _instance;
}+(instancetype)shareTool{return [[self alloc]init];}(id)copyWithZone:(NSZone *)zone{return _instance;}(id)mutableCopyWithZone:(NSZone *)zone{return _instance;}#warning 可能遇到其他人员 (要一会设置ARC,一会设置MRC),如何处理(可以判断当前项目是不是MRC 如果是MRC才编译下面一段的代码)/*使用条件编译#if// 条件满足 ARC#else// 非ARC#endif根据一个宏去判断当前项目是不是 ARCARC : __has_feature(objc_arc)*/#if __has_feature(objc_arc)// 条件满足 ARC#else// 否则#pragma MRC模式 存储单例模式#pragma mark 1. 重写release方法(oneway void)release{}#pragma mark 2. 重写retain方法(instancetype)retain{return _instance;}#pragma mark 3. 重写retainCount方法// 习惯 (一般返回最大值 : MAXFLOAT)(NSUInteger)retainCount{return MAXFLOAT;}#endif@end
#import "ViewController.h"#import "LYHTool.h"@interface ViewController ()@end@implementation ViewController/*单例模式 : 永远只有一次实例*/-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{LYHTool t1 = [[LYHTool alloc]init];//    [t1 release];/release -1retain + 1-[LYHTool init]: message sent to deallocated instance 0x608000017740*/LYHTool *t2 = [[LYHTool alloc]init];LYHTool *t3 = [LYHTool new];LYHTool *t4 = [LYHTool shareTool];LYHTool *t5 = [t1 copy]; //LYHTool *t6 = [t1 mutableCopy]; //
NSLog(@"\nt1 %p \nt2 %p\nt3 %p\nt4 %p\nt5 %p\nt6 %p",t1,t2,t3,t4,t5,t6);
#if __has_feature(objc_arc)NSLog(@"ARC");#elseNSLog(@"MRC");#endif}/**没有登录情况下 可以使用单例*/@end

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