美文网首页iOS开发
objective-c static变量的使用总结

objective-c static变量的使用总结

作者: a626648791b2 | 来源:发表于2016-10-17 14:10 被阅读105次

在objective-c 中,需要在.m文件里面定义个static变量来表示全局变量 static变量只是在编译时候进行初始化,对于static变量,无论是定义在方法体里面 还是在方法体外面其作用域都一样

在我们经常使用的UITableViewController里面,在定义UITableCellView的时候,模板经常会使用以下代码

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

return cell;

}

在上面定义了static变量,这个变量在编译期会对这个变量进行初始化赋值,也就是说这个变量值要么为nil,要么在编译期就可以确定其值,一般情况下,只能用NSString或者基本类型,并且这个变量只能在cellForRollAtIndexPath访问

void counter{
 
static int count = 0;
 
count ++;
 
}
 
counter();
 
counter();

上面代码执行完成之后,第一次count的值为1,第二次调用count 的值为2

static变量也可以定义在.m的方法体外,这样所有的方法内部都可以访问这个变量。但是在类之外是没有办法的,也就是说不能用 XXXClass.staticVar 的方式来访问 staticVar变量。也就是说static变量都是私有的。

如果.m文件和方法里面定义了同名的static变量,那么方法体里面的实例变量和全局的static变量不会冲突,在方法体内部访问的static变量和全局的static变量是不同的


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@implementation IFoundAppDelegate
 
static NSString * staticStr  = @"test";
 
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
 
{
 
static NSString * staticStr  = @"test2";
 
NSLog(@"the staticStr is %@ -- %d",staticStr,[staticStr hash]);
 
}
 
- (void)applicationWillResignActive:(UIApplication *)application
 
{
 
NSLog(@"the staticStr is %@ -- %d",staticStr,[staticStr hash]);
 
}

以上两个static变量是两个不同的变量,在didFinishLaunchingWithOptions方法内部,访问的是方法体内部定义的staticStr变量,在applicationWillResignActive方法体里面,访问的全局定义的staticStr变量。可以通过日志打印其hash来进行确认两个变量是否一样。

感谢GodIsCoder http://www.cnblogs.com/aigongsi/archive/2013/01/25/2876025.html

相关文章

  • objective-c static变量的使用总结

    在objective-c 中,需要在.m文件里面定义个static变量来表示全局变量 static变量只是在编译...

  • const static

    Static 表明变量的可见范围,在objective-c 的 .m文件的顶端中,使用该关键字,表明该变量的作用域...

  • Objective-C中static关键字

    Objective-C中static关键字 在Java中的某个类声明一个static的静态变量,其他类中想使用或者...

  • iOS---static变量的使用总结

    在objective-c中,需要在.m文件里定义static变量来表示全局变量,但此static变量只是在编译时候...

  • OC中static、const、extern关键字理解

    static关键字 static关键字用于修饰变量。 static修饰局部变量当使用static修饰局部变量时, ...

  • java之面向对象2

    static: 1.static使用之静态变量: 语法:static 类型名 变量名; Java 中被 stati...

  • 3.3类ThreadLocal的使用

    变量值的共享可以使用public static变量的形式,所有的线程都使用同一个public static变量。如...

  • extern static const inline

    static static 可以用来修饰静态变量,在iOS中,如果使用static修饰全局变量,则全局变量只能在当...

  • 变量Variable介绍:2-静态变量static

    在Objective-C中,在变量声明前加上关键字static,该变量就成为静态变量。静态变量的作用可以使局部变量...

  • Java中的静态内部类

    一:静态内部类 使用static修饰的变量是静态变量,使用static 修饰的方法是静态方法,静态变量和静态方法都...

网友评论

    本文标题:objective-c static变量的使用总结

    本文链接:https://www.haomeiwen.com/subject/ohnayttx.html