1

I have a configuration .h file , which i get access to, from another classes by import it to them .

In that .h class , i have that :

static NSString *const charIdList[] =
{

    @"1", @"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"AA",@"BB",@"CC",@"DD",@"EE",@"FF",@"GG",@"HH",@"II",@"J",@"K"
};

Which i use in other classes during the program run. Should i use the static variable here ? or using only a string will be safe ? What is the scope of the NSString in that case-if it will not be static ?

4

1 回答 1

4

您需要注意static在头文件中定义变量的影响:发生这种情况时,包含您的头文件的每个翻译单元1将获得自己的charIdList数组副本,无论您是否使用它。

更好的方法是将此数组建立为单例,或者如果它确实是一个常量,则将其定义为全局,并extern在标题2中为它添加一个:

.h 文件:

extern NSString *const charIdList[];
extern size_t charIdListLength;

.m 文件:

NSString *const charIdList[] = {
    @"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"AA",@"BB",@"CC",@"DD",@"EE",@"FF",@"GG",@"HH",@"II",@"J",@"K"
};
size_t charIdListLength = sizeof(charIdList)/sizeof(charIdList[0]);


1 “翻译单元”是一个.c.m文件的花哨名称。

2注意数组的长度如何需要单独定义;否则,分割sizeofs 的技巧将不起作用。

于 2013-09-19T16:31:21.507 回答