How to use static variables in Objective-cThe use of
static variables in
objective-c is what this article describes,
objective-c supports global
variables , there are two main ways of implementation: the first and C + +, using the "extern" keyword; Another is to use a singleton implementation. (for example, we often put a
variable in the appdelegate as a global
variable to access, Where Appdelegate is a singleton class )
How do you implement static member variables like C + + in Objective-c?
What you need to do is to define a static variable in a implementation (. m or. mm) file of Class A, and then manipulate the variable for the Class A by defining a static member function (class method, also known as a type). So in other classes you don't need to create an instance of Class A to access the static variable. While this static variable is not a static member variable of Class A, it also achieves the same effect . The scope of the static variable is limited to a single file . The code can resemble the following:
Example.h
@interface Example:nsobject {
}
-(ID) init;
+ (int) InstanceCount;
@end
Example.m
#import "Example.h"
static int count;
@implementation Example
-(ID) init{
self = [super init];
if (nil!=self) {
Count+=1;
}
return self;
}
+ (int) instancecount{
return count;
}
@end
Example.h
@interface Example:nsobject {
}
-(ID) init;
+ (int) InstanceCount;
@end
Example.m
#import "Example.h"
static int count;
@implementation Example
-(ID) init{
self = [super init];
if (nil!=self) {
Count+=1;
}
return self;
}
+ (int) instancecount{
return count;
}
@end
In the example above, you can access the static variable count by [Example InstanceCount] without creating an instance.
Objective-c static Variable use method