Objective-c static Variable use method

Source: Internet
Author: User


 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


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.