亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

iOS關(guān)鍵字static extern const使用示例詳解

 更新時間:2023年11月09日 11:02:53   作者:FieryDragon  
這篇文章主要為大家介紹了iOS關(guān)鍵字static extern const使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

全局變量

在函數(shù)外聲明的變量,可以在聲明時附上初始值,存儲在全局區(qū),生命周期為整個程序運行期間。

#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
SEString2

static - 靜態(tài)全局變量

用static修飾的全局變量為靜態(tài)全局變量,存儲在全局區(qū),生命周期為整個程序運行期間。

#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
@end

static不能與extern組合使用,否則報錯:Cannot combine with previous 'extern' declaration specifier

聲明在.h文件時,引入該類,依然可以使用并修改此靜態(tài)全局變量;

聲明在.m文件時,兩個類文件可是使用相同變量名,彼此相互獨立。

全局變量和靜態(tài)變量區(qū)別(摘抄)

兩者的區(qū)別雖在于非靜態(tài)全局變量的作用域是整個源程序,當一個源程序由多個源文件組成時,非靜態(tài)的全局變量在各個源文件中都是有效的。 而靜態(tài)全局變量則限制了其作用域,即只在定義該變量的源文件內(nèi)有效,在同一源程序的其它源文件中不能使用它。由于靜態(tài)全局變量的作用域局限于一個源文件內(nèi),只能為該源文件內(nèi)的函數(shù)公用,因此可以避免在其它源文件中引起錯誤。

const

const修飾的變量是不可變的。

正確用法:

static NSString * const SEString = @"SEString";

以下兩種寫法const修飾的是* SEString,*是指針指向符,也就是說此時指向內(nèi)存地址是不可變的,而內(nèi)存保存的內(nèi)容時可變的。

static NSString const * SEString = @"SEString";
static const NSString * SEString = @"SEString";

局部變量

函數(shù)內(nèi)部聲明的變量,僅在當前函數(shù)執(zhí)行期間存在。

@implementation SEObject

- (void)add {
    NSInteger a = 1;
    NSInteger b = 2;
    NSInteger c = a+b;
    NSLog(@"c = %ld",c);
}

@end

static - 靜態(tài)局部變量

用static修飾的局部變量為靜態(tài)局部變量,存儲在全局區(qū),生命周期為整個程序運行期間。

- (void)add {
    NSInteger a = 1;
    NSInteger b = 2;
    static NSInteger c2;
    c2 += a+b;
    NSLog(@"c2 = %ld",c2);
}
調(diào)用兩次結(jié)果:
c2 = 3
c2 = 6

以上就是iOS關(guān)鍵字static extern const使用示例詳解的詳細內(nèi)容,更多關(guān)于iOS關(guān)鍵字static extern const的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論