Swift single-instance mode implementation and class method

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.