全局变量
在函数外声明的变量,可以在声明时附上初始值,存储在全局区,生命周期为整个程序运行期间。
#import "seobject.h" //定义在.h文件中时该类被其他文件引入时报重复定义的错误(1 duplicate symbol for architecture x86_64) nsstring * sestring = @"sestring"; @implementation seobject @end
#import "seview.h" //#import "seobject.h" //nsstring * sestring; @implementation seview @end
源程序中不能存在相同的对象名,否则编译器报错(1 duplicate symbol for architecture x86_64)
extern
此时如果其它源文件想要访问该全局变量,需要声明extern。
- 在使用的类中
extern 全局变量,此时不要要引入全局变量所在类。
#import "seview.h"
//#import "seobject.h"
//nsstring * sestring;
@implementation seview
- (void)add {
extern nsstring * sestring;
nslog(@"%@",sestring);
sestring = @"sestring2";
nslog(@"%@",sestring);
}
@end- 在全局变量所在类的
.h文件中声明该全局变量外部使用(推荐)。
#import <foundation/foundation.h> ns_assume_nonnull_begin extern nsstring * sestring; @interface seobject : nsobject @end ns_assume_nonnull_end
#import "seview.h"
#import "seobject.h"
//nsstring * sestring;
@implementation seview
- (void)add {
//extern nsstring * sestring;
nslog(@"%@",sestring);
sestring = @"sestring2";
nslog(@"%@",sestring);
}
@end
sestring
sestring2static - 静态全局变量
用static修饰的全局变量为静态全局变量,存储在全局区,生命周期为整个程序运行期间。
#import "seobject.h"
//定义在.h文件中时该类被其他文件引入时报重复定义的错误(1 duplicate symbol for architecture x86_64)
static nsstring * sestring = @"sestring";
@implementation seobject
+ (void)add {
nslog(@"%@",sestring);
sestring = @"sestring2";
nslog(@"%@",sestring);
}
sestring
sestring2
@endstatic不能与extern组合使用,否则报错:cannot combine with previous 'extern' declaration specifier
声明在.h文件时,引入该类,依然可以使用并修改此静态全局变量;
声明在.m文件时,两个类文件可是使用相同变量名,彼此相互独立。
全局变量和静态变量区别(摘抄)
两者的区别虽在于非静态全局变量的作用域是整个源程序,当一个源程序由多个源文件组成时,非静态的全局变量在各个源文件中都是有效的。 而静态全局变量则限制了其作用域,即只在定义该变量的源文件内有效,在同一源程序的其它源文件中不能使用它。由于静态全局变量的作用域局限于一个源文件内,只能为该源文件内的函数公用,因此可以避免在其它源文件中引起错误。
const
const修饰的变量是不可变的。
正确用法:
static nsstring * const sestring = @"sestring";
以下两种写法const修饰的是* sestring,*是指针指向符,也就是说此时指向内存地址是不可变的,而内存保存的内容时可变的。
static nsstring const * sestring = @"sestring"; static const nsstring * sestring = @"sestring";
局部变量
函数内部声明的变量,仅在当前函数执行期间存在。
@implementation seobject
- (void)add {
nsinteger a = 1;
nsinteger b = 2;
nsinteger c = a+b;
nslog(@"c = %ld",c);
}
@end
static - 静态局部变量
用static修饰的局部变量为静态局部变量,存储在全局区,生命周期为整个程序运行期间。
- (void)add {
nsinteger a = 1;
nsinteger b = 2;
static nsinteger c2;
c2 += a+b;
nslog(@"c2 = %ld",c2);
}
调用两次结果:
c2 = 3
c2 = 6以上就是ios关键字static extern const使用示例详解的详细内容,更多关于ios关键字static extern const的资料请关注代码网其它相关文章!
发表评论