在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
网友评论