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.