Objective C - 如何定义类中所有方法都可以访问的静态数字数组?

发布于 2024-09-14 18:22:44 字数 37 浏览 8 评论 0原文

我如何定义一个可由我的类中的所有方法访问的静态数字数组???

How can i define a STATIC array of numbers accessible to all methods in my class???

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅唱々樱花落 2024-09-21 18:22:44

与在 C 中执行此操作的方式相同:

static int myArray[] = { 0, 1, 2, 3, 4, 5 };

如果您想要一个静态 NSArray,则必须采取一些技巧。 Objective-C 中的对象类型不允许使用 static (因为你不能直接声明对象 - 只能声明指针)。在这种情况下,您需要阅读 Objective-C 单例。实现它的快速方法:

+ (NSArray *)myArray
{
  static NSArray *theArray;
  if (!theArray)
  {
    theArray = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:0], nil];
  }
  return theArray;
}

当然,您可以将其设置为使用您想要的任何类型的对象进行初始化。

The same way you'd do it in C:

static int myArray[] = { 0, 1, 2, 3, 4, 5 };

If you want a static NSArray, you'll have to do some tricks. static isn't allowed for object types in Objective-C (since you can't declare an object directly - only pointers). In that case, you need to read up on Objective-C singletons. A quick way to implement it:

+ (NSArray *)myArray
{
  static NSArray *theArray;
  if (!theArray)
  {
    theArray = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:0], nil];
  }
  return theArray;
}

You can, of course, set it up to initialize with whatever kind of objects you'd like.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文