目标 C 中的静态初始值设定项 [英] static initializers in objective C

查看:63
本文介绍了目标 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.

推荐答案

由于 NSArraysMyObjectTypes 是堆分配的对象,您不能在静态上下文中创建它们.您可以声明变量,然后在方法中初始化它们.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆