Static variables in objective-C

Source: Internet
Author: User

Objective-C supports global variables. There are two main implementation methods: the first one is the same as that in C/C ++, and the "extern" keyword is used; the other is the singleton implementation. (For example, we often put a variable in appdelegate as a global variable for access. appdelegate is a singleton class)

 

In objective-C, how does one implement static member variables like in C ++?

What you need to do is in the implementation (. m or. mm) file defines a static variable, and then defines a static member function (class method, that is, class method) for Class A to operate on the variable. In this way, you do not need to create a class A instance to access static variables in other classes. Although this static variable is not a static member variable of Class A, it achieves the same effect. The scope of static variables is limited to a single file.CodeIt can be as follows:

// Example. h <br/> @ interface Example: nsobject {</P> <p >}</P> <p>-(ID) Init; <br/> + (INT) instancecount; </P> <p> @ end </P> <p> // example. m <br/> # import "example. H "</P> <p> static int count; </P> <p> @ implementation example <br/>-(ID) init {<br/> Self = [Super init]; <br/> If (nil! = Self) {<br/> count + = 1; <br/>}< br/> return self; <br/>}</P> <p> + (INT) instancecount {<br/> return count; <br/>}</P> <p> @ end <br/>

In the preceding example, you can use [Example instancecount] to access the static variable count without creating an instance.

Related Article

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.