Static修饰局部变量:
1、当static关键字修饰局部变量时,只会初始化一次。
例 1
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
[self test];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
NSLog(@"---------- viewWillAppear -------------");
[self test];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSLog(@"---------- viewDidAppear -------------");
[self test];
}
- (void)test {
NSString *normalString;
static NSString *staticString;
NSLog(@"normal = %p, static = %p", &normalString, &staticString);
}
![](https://img.haomeiwen.com/i4986510/f4ad54d730dce2ca.jpg)
2、当static关键字修饰局部变量时,在程序中只有一份内存。
例 2:
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
[self test];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
NSLog(@"---------- viewWillAppear -------------");
[self test];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSLog(@"---------- viewDidAppear -------------");
[self test];
}
- (void)test {
NSString *normalString;
static NSString *staticString;
NSLog(@"normal = %p, static = %p", &normalString, &staticString);
}
@end
![](https://img.haomeiwen.com/i4986510/b4b67ddcefba1018.png)
从打印结果可以看出,Static修饰的局部变量在程序中只有一份内存(如图结果:0x104358ef8)。
Static修饰全局变量:
默认情况下,全局变量在整个程序中是可以被访问的(即全局变量的作用域是整个项目文件)
#import "SLStaticDemo.h"
static NSInteger age;
@implementation SLStaticDemo
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
age = 20;
NSLog(@"age = %ld", (long)age);
}
Extern关键字
#import "SLStaticDemo.h"
NSInteger age = 10;
@implementation SLStaticDemo
@end
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
extern NSInteger age;
NSLog(@"age = %ld", (long)age);
age += 10;
NSLog(@"age = %ld", (long)age);
}
@end
![](https://img.haomeiwen.com/i4986510/b4ac0e60dae65426.png)
从输出结果 age = 10 我们可以看到,在ViewController.m中并没有import SLStaticDemo.h也能得到,说明extern可以访问全局变量
总结:
static关键字修饰局部变量:
当static关键字修饰局部变量时,只会初始化一次且在程序中只有一份内存;
static关键字修饰全局变量:
默认情况下,全局变量在整个程序中是可以被访问的(即全局变量的作用域是整个项目文件)
static和const使用代替宏:如果使用static和const组合使用,不可以修改变量的值,否则编译器报错:
static NSString * const demo = @"www.baidu.com";
extern关键字:
想要访问全局变量可以使用extern关键字
全局变量是不安全的,因为它可能会被外部修改,所以在定义全局变量时推荐使用static关键字修饰。
网友评论