博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
IOS开发中单例模式使用详解
阅读量:4347 次
发布时间:2019-06-07

本文共 2151 字,大约阅读时间需要 7 分钟。

第一、基本概念

单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例类的特殊类。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问。

第二、在IOS中使用单例模式的情况

1.如果说创建一个对象会耗费很多系统资源,那么此时采用单例模式,因为只需要一个实例,会节省alloc的时间

2.在IOS开发中,如果很多模块都要使用同一个变量,此时如果把该变量放入单例类,则所有访问该变量的调用变得很容易,否则,只能通过一个模块传递给另外一个模块,这样增加了风险和复杂度

第三、创建单例模式的基本步骤

1.声明一个单例对象的静态实例,并初始化为nil

2.声明一个类的工厂方法,生成一个该类的实例,并且只会生成一个

3.覆盖allcoWithZone方法,确保用户在alloc 时,不会产生一个多余的对象

4.实现NSCopying协议,覆盖release,autorelease,retain,retainCount方法,以确保只有一个实例化对象

5.在多线程的环境中,注意使用@synchronized关键字 

 

////  UserContext.h//  SingleDemo////  Created by andyyang on 9/30/13.//  Copyright (c) 2013 andyyang. All rights reserved.//#import 
@interface UserContext : NSObject@property (nonatomic,retain) NSString *username;@property(nonatomic,retain)NSString *email;+(id)sharedUserDefault;@end

 

 

 

////  UserContext.m//  SingleDemo////  Created by andyyang on 9/30/13.//  Copyright (c) 2013 andyyang. All rights reserved.//#import "UserContext.h"static UserContext *singleInstance=nil;@implementation UserContext+(id)sharedUserDefault{    if(singleInstance==nil)    {        @synchronized(self)        {            if(singleInstance==nil)            {                singleInstance=[[[self class] alloc] init];                            }        }    }    return singleInstance;}+ (id)allocWithZone:(NSZone *)zone;{    NSLog(@"HELLO");if(singleInstance==nil){    singleInstance=[super allocWithZone:zone];}    return singleInstance;}-(id)copyWithZone:(NSZone *)zone{    NSLog(@"hello");    return singleInstance;}-(id)retain{    return singleInstance;}- (oneway void)release{}- (id)autorelease{    return singleInstance;}- (NSUInteger)retainCount{    return UINT_MAX;}@end

 

#import 
#import "UserContext.h"int main(int argc, const char * argv[]){ @autoreleasepool { UserContext *userContext1=[UserContext sharedUserDefault]; UserContext *userContext2=[UserContext sharedUserDefault]; UserContext *userContext3=[[UserContext alloc] init]; UserContext *userContext4=[userContext1 copy]; // insert code here... NSLog(@"Hello, World!"); } return 0;}

result:

 

转载于:https://www.cnblogs.com/james1207/p/3348008.html

你可能感兴趣的文章
iOS中copy和strong修饰变量的区别
查看>>
IRP的同步
查看>>
【Android】you must restart adb and eclipse 问题解决备忘
查看>>
Myeclipse 优化
查看>>
Python生成器与yield
查看>>
iOS定位与地图
查看>>
ELK(elasticsearch+logstash+kibana)实现Java分布式系统日志分析架构
查看>>
My first essay
查看>>
MFC、SDK和API有什么区别
查看>>
一套实用的渗透测试岗位面试题
查看>>
gitHub新项目的上传
查看>>
DIY.NETORM框架——总体分析
查看>>
17款提高编程效率的css工具
查看>>
一个form表单有两个按钮,分别提交到不同的页面
查看>>
Shiro(一):Shiro介绍及主要流程
查看>>
应用程序本地化之文本本地化
查看>>
Hadoop快照介绍
查看>>
hibernate 实现多表连接查询
查看>>
Ubuntu一些常用的软件安装及配置
查看>>
最后还是走到了二战这一步3.30-4.5
查看>>