目标 C 中的静态初始值设定项 [英] static initializers in objective C
问题描述
如何在objective-c 中创建静态初始值设定项(如果我的术语正确的话).基本上我想做这样的事情:
How do I make static initializers in objective-c (if I have the term correct). Basically I want to do something like this:
static NSString* gTexts[] =
{
@"A string.",
@"Another string.",
}
但我想做这个更像结构的事情,即对于这个数组中的每个元素,不仅有一个 NSString,而是一个 NSString 加上一个包含可变数量的 MyObjectType 的 NSArray,其中 MyObjectType 将包含一个 NSString,一对整数等
But I want to do this more struct-like, i.e. have not just an NSString for each element in this array, but instead an NSString plus one NSArray that contains a variable number of MyObjectType where MyObjectType would contain an NSString, a couple ints, etc.
推荐答案
由于 NSArrays
和 MyObjectTypes
是堆分配的对象,您不能在静态上下文中创建它们.您可以声明变量,然后在方法中初始化它们.
Since NSArrays
and MyObjectTypes
are heap-allocated objects, you cannot create them in a static context. You can declare the variables, and then initialize them in a method.
所以你不能这样做:
static NSArray *myStaticArray = [[NSArray alloc] init....];
相反,您必须:
static NSArray *myStaticArray = nil;
- (void) someMethod {
if (myStaticArray == nil) {
myStaticArray = [[NSArray alloc] init...];
}
}
这发生适用于常量字符串(@"foo"
等),因为它们不是堆分配的.它们被硬编码到二进制文件中.
This happens to work with constant strings (@"foo"
, etc), because they are not heap-allocated. They are hardcoded into the binary.
这篇关于目标 C 中的静态初始值设定项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!