Objective-C中静态变量使用方法是本文要介绍的内容,Objective-C 支持全局变量,主要有两种实现方式:***种和C/C++中的一样,使用"extern"关键词;另外一种就是使用单例实现。(比如我们经常会把一个变量放在AppDelegate里面作为全局变量来访问,其中AppDelegate就是一个单例类)
在Objective-C中如何实现像C++中那样的静态成员变量呢?
你需要做的是在一个类A的implementation(.m或者.mm)文件中定义一个static变量,然后为A类定义静态成员函数(class method,也就是类方法)来操作该变量。这样在其它类中你就不需要创建A类的实例来对static变量进行访问。虽然该static变量并不是A类的静态成员变量,但是也算达到了同样的效果。static变量的作用域被限制在单一的文件中。代码可以如下所示:
//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
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
上面的例子中你就可以通过[Example instanceCount]对静态变量count进行访问,无须创建实例。
小结:详解Objective-C中静态变量使用方法的内容介绍完了,希望通过本文的学习对你有所帮助