swift 中单例的写法

在swift中单例的写法和oc的有所不同,在书写的时候又分很多种写法,,如果一个.swift 文件只创建了一个类,可以用那种dispatch_once的写法,如果一个.swift文件中有很多类的存在,则会报错,需要写成下边的写法,这样页更加的简单

在底部声明静态属性

1 static var resourceBundle :NSBundle?

在函数中实现

1     //MARK: ------- 微博图片资源 bundle--------
2     class func bundle() -> NSBundle
3     {
4         if self.resourceBundle == nil {
5             self.resourceBundle = NSBundle(path: NSBundle.mainBundle().pathForResource("ResourceWeibo", ofType: "bundle")!)!
6         }
7         return self.resourceBundle!
8     }

这样就非常简单地实现了单例写法,即使这个类被反复创建 ,单例属性也只会被生成一次

时间: 2024-08-24 09:00:57

swift 中单例的写法的相关文章

Swift单例的写法

Swift单例的写法 by 伍雪颖 override func viewDidLoad() { super.viewDidLoad() let instance = SingletonClass.shared } class SingletonClass { class var shared: SingletonClass { struct Static { static let instance: SingletonClass = SingletonClass() } return Stati

swift-单例的写法

OC 中单例的使用 + (instancetype)sharedManager { static id instance; static dispatch_once_t onceToken; NSLog(@"%ld", onceToken); dispatch_once(&onceToken, ^{ instance = [[self alloc] init]; }); return instance; } swift 中单例的使用 static var instance: N

iOS开发中单例对象的标准创建方法

//标准的单例写法 //以创建歌曲的管理者为例进行创建.+(instancetype) sharedQYSongManager { static QYSongsManager *songManager =nil; //采用GDC标准单例实现方法 static dispatch_once_t onceToken; //Executes a block object once and only once for the lifetime of an application. dispatch_onc

OC & Swift 单例

1. OC 单例 + (NetworkTool *)sharedNetworkTool { static id instace; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ instace = [[self alloc] init]; }); return instace; } 2. Swift 单例 private static let instance = NetworkTool() class func sh

单例的写法

1. #import "MySingleton.h" static MySingleton *_singleton = nil; + (id)shareObject { @synchronized(self){ if (_singleton == nil) { _singleton = [[MySingleton alloc] init]; } } return _singleton; } @end @synchronized 的作用是创建一个互斥锁,保证此时没有其它线程对self对象

IOS中单例的简单使用

单例的写法,需要用到GCD.如下: 在.h中 @interface JFSingleton : NSObject @property(nonatomic,copy) NSString *tempStr; ///类方法 +(JFSingleton *) sharedInstance; @end 在.m中,有两种写法.dispatch_once是线程安全的,保证多线程时最多调用一次 方法一: 1 @implementation JFSingleton 2 3 static JFSingleton *

C#中单例的实现方法

本文实例讲述了C#中单例的实现方法.分享给大家供大家参考.具体实现方法如下: 代码如下: #region "实现这个窗口类的单例,单例类常用于被主窗口以show()方法打开的窗口,使用单例后只会打开一个此类的对象" //1.私有化构造函数,使在外部不能new(开辟堆空间,创建对象,调用构造函数) private FStudentMan() { InitializeComponent(); } //2.创建一个静态的私有的窗体类的变量 private static FStudentMan

swift中editingStyleForRowAtIndexPath的写法

效果图: 首先要实现这句tableView.setEditing(true, animated: true)才能弹出左侧的小圆圈 然而在oc中tableview删除的写法百度一下很常见但是swift中包的很严实: override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle { return U

java中单例设计模式

在java中创建单例的方式主要有三种:饿汉式.懒汉式.登记式.以下内容均是摘抄自 http://blog.csdn.net/jason0539/article/details/23297037/ 一.懒汉式 //懒汉式单例类.在第一次调用的时候实例化自己 public class Singleton { private Singleton() {} private static Singleton single=null; //静态工厂方法 public static Singleton get