详解Objective-C中静态变量使用方法

移动开发 iOS
在Objective-C中如何实现像C++中那样的静态成员变量呢?你需要做的是在一个类A的implementation(.m或者.mm)文件中定义一个static变量,然后为A类定义静态成员函数(class method,也就是类方法)来操作该变量。

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静态变量使用方法的内容介绍完了,希望通过本文的学习对你有所帮助

责任编辑:zhaolei 来源: 互联网
相关推荐

2011-07-19 17:18:35

Objective-C Property

2011-08-02 15:55:31

Objective-C NSAutorele

2011-08-10 11:08:32

Objective-C字符串NSString

2011-08-17 11:05:22

Objective-C方法

2011-08-22 15:31:35

Objective-C协议

2011-08-04 09:56:30

Objective-C 变量 数据类型

2011-07-27 16:36:03

iphone Objective- 静态库

2011-08-16 10:23:04

Objective-CNSAutoreleaXcode常用键

2011-08-15 17:47:13

Objective-CisMemberOfC

2011-07-08 18:44:09

Objective-C Self Super

2011-07-29 16:16:30

Objective-c block

2011-08-17 10:58:59

Objective-C构造函数

2011-07-27 16:18:42

Objective-c 协议

2011-07-18 16:36:51

Objective-C XCode

2015-10-08 10:01:10

Objective-CLayout

2014-04-01 10:50:42

iOS开发runtimeObjective-C

2011-08-04 17:13:48

Objective-C 字符串

2011-08-17 10:29:39

Objective-C预处理

2023-10-07 15:53:05

C/C++静态变量内存

2011-08-04 13:38:01

Objective-C C++
点赞
收藏

51CTO技术栈公众号