iOS App开发中使用设计模式中的单例模式的实例解析
2019/7/9 23:18:02
本文主要是介绍iOS App开发中使用设计模式中的单例模式的实例解析,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
一、单例的作用
顾名思义,单例,即是在整个项目中,这个类的对象只能被初始化一次。它的这种特性,可以广泛应用于某些需要全局共享的资源中,比如管理类,引擎类,也可以通过单例来实现传值。UIApplication、NSUserDefaults等都是IOS中的系统单例。
二、单例模式的两种写法
1,常用写法
#import "LGManagerCenter.h" static LGManagerCenter *managerCenter; @implementation LGManagerCenter +(LGManagerCenter *)sharedManager{ if(!managerCenter) managerCenter=[[self allocWithZone:NULL] init]; return managerCenter; } @end
2,用GCD创建单例类
#import "LGManagerCenter.h" @implementation LGManagerCenter +(LGManagerCenter *)sharedManager{ static dispatch_once_t predicate; static LGManagerCenter * managerCenter; dispatch_once(&predicate, ^{ managerCenter=[[LGManagerCenter alloc] init]; }); return managerCenter; } @end
其中dispatch_once函数只执行一次。
三、代码的优化
通过上面的方法,我们已经可以使用类方法来得到这个单例,但很多时候,项目的工程量很大,还有可能会很多开发者同时参与一个项目的开发,为了安全与管理代码的方便,也为了给不是这个单例的创作者但会用到这个单例的开发人员一些提示,我们通常会重写一些方法:
首先我们自己实现一个alloc方法:
+(instancetype)myAlloc{ return [super allocWithZone:nil]; }
将我们的单例实现方法略作修改:
+(ZYHPayManager *)sharedMamager{ static ZYHPayManager * manager; if (manager==nil) { manager=[[ZYHPayManager myAlloc]init]; } return manager; }
将一些视图实例化对象的方法重写:
+(instancetype)alloc{ NSAssert(0, @"这是一个单例对象,请使用+(ZYHPayManager *)sharedMamager方法"); return nil; } +(instancetype)allocWithZone:(struct _NSZone *)zone{ return [self alloc]; } -(id)copy{ NSLog(@"这是一个单例对象,copy将不起任何作用"); return self; } +(instancetype)new{ return [self alloc]; }
注意:这里的alloc使用了断言,让任何视图通过alloc创建对象的程序段断在此处,给程序员提示。copy方法这里只是简单的返回了原对象,并未做任何处理,打印信息给程序员提示。
这篇关于iOS App开发中使用设计模式中的单例模式的实例解析的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-08-29Axios库资料:新手入门指南与基本使用教程
- 2024-03-14system bios shadowed
- 2024-03-14gabios
- 2024-02-07iOS应用提交上架的最新流程
- 2024-02-06打包 iOS 的 IPA 文件
- 2023-12-07uniapp打包iOS应用并通过审核:代码混淆的终极解决方案 ?
- 2023-11-25uniapp IOS从打包到上架流程(详细简单) 原创
- 2023-11-10【iOS开发】iOS App的加固保护原理:使用ipaguard混淆加固
- 2023-09-30最强大的iOS应用源码保护工具:Ipa Guard,保护你的商业机密代码
- 2023-09-07iOS安全加固探讨:代码混淆、类名方法名混淆等方法