Let's talk about the class method before we start the singleton mode. The singleton mode needs to rely on the class method to implement
First, we know that the class method is called directly using the class name, without having to build the object and then call it.
In fact, the generation of the class method is very simple, only need to give our previous object method with the class keyword to decorate can
Let's look at an example
Object methods
Func userName ()->string{ return "Zhangsan" }
Class method
Class Func UserName ()->string{ return "Zhangsan" }
Let's start with a singleton pattern.
First, the singleton mode is generally used for data sharing, which saves resources when it is used without creating multiple objects. For example, the nsuserdefault of our attributes is a singleton
Next we implement a class that is used to share data. Named Mytool
Implemented as follows
Class mytool{ var currentnum:int=1 struct Toolp { static var mytool:mytool?=nil } class Func Sharemytool ()->mytool { if (Toolp.mytool = = nil) { toolp.mytool=mytool () } return toolp.mytool! } }
Use the following
var mytool=mytool.sharemytool () mytool.currentnum=10 var mytool1=mytool.sharemytool () println ( Mytool1.currentnum)
We first create an object Mytool change the variable currentnum in the class to 10
And then we're going to print out the object (actually, the object we created last time) and find out that he's just 10 currentnum.
Okay, just a little bit easier, we can continue to play on their own, there are problems can be added group discussion
Apple Development Group: 414319235 Welcome to join the Welcome discussion question
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Swift single-instance mode implementation and class method