zoukankan      html  css  js  c++  java
  • Objective-C 静态变量 使用方法

     

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

    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变量的作用域被限制在单一的文件中。代码可以如下所示:

    1. //example.h     
    2. @interface Example : NSObject {    
    3.     
    4. }    
    5.     
    6. - (id)init;    
    7. +(int)instanceCount;    
    8.     
    9. @end    
    10.     
    11. //example.m     
    12. #import "example.h"     
    13.     
    14. static int count;    
    15.     
    16. @implementation Example    
    17. -(id)init{    
    18. self = [super init];    
    19. if(nil!=self){    
    20. count+=1;    
    21. }    
    22. return self;    
    23. }    
    24.     
    25. +(int)instanceCount{    
    26. return count;    
    27. }    
    28.     
    29. @end    
    30. //example.h  
    31. @interface Example : NSObject {  
    32.  
    33. }  
    34.  
    35. - (id)init;  
    36. +(int)instanceCount;  
    37.  
    38. @end  
    39.  
    40.  
    41. //example.m  
    42. #import "example.h"  
    43.  
    44. static int count;  
    45.  
    46. @implementation Example  
    47. -(id)init{  
    48. self = [super init];  
    49. if(nil!=self){  
    50. count+=1;  
    51. }  
    52. return self;  
    53. }  
    54.  
    55. +(int)instanceCount{  
    56. return count;  
    57. }  
    58. @end 

    上面的例子中你就可以通过[Example instanceCount]对静态变量count进行访问,无须创建实例。

     
  • 相关阅读:
    关于学习netty的两个完整服务器客户端范例
    android-betterpickers
    ValueBar
    CircleDisplay
    JellyViewPager
    十天学习PHP之第二天
    android-測试so动态库(九)
    实习题
    android 编程小技巧(持续中)
    Codeforces Round #253 (Div. 2)——Borya and Hanabi
  • 原文地址:https://www.cnblogs.com/iOS-mt/p/4227297.html
Copyright © 2011-2022 走看看