`
rysh0818
  • 浏览: 21875 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

objective-c static变量的使用总结

阅读更多

在java中,我们经常使用的是单例模式,这些设计模式在ios开发中也比较常用,最近也在考虑使用在ios开发中使用单例模式

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

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

1
2
3
4
5
6
7
8
9
10
11
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
return cell;
}

在上面 定义了static变量,这个变量在编译期会对这个变量进行初始化赋值,也就是说这个变量值要么为nil,要么在编译期就可以确定其值,一般情况下,只能用NSString或者基本类型 ,并且这个变量只能在cellForRowAtIndexPath 访问,这个变量和java里面的static属性一样,但是java的static属性是可以在java类里面的任何访问,定义在方法体里面的static变量只能在 对应的访问里面访问,但是变量确是类变量。这个和C语言里面的static的变量属性一样。

1
2
3
4
5
6
7
8
9
10
11
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来进行确认两个变量是否一样。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics