如何在 Objective-c 中将数组声明为常量? [英] How do I declare an array as a constant in Objective-c?

查看:36
本文介绍了如何在 Objective-c 中将数组声明为常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码给了我错误:

//  constants.h
extern NSArray const *testArray;

//  constants.m
NSArray const *testArray = [NSArray arrayWithObjects:  @"foo", @"bar", nil];

我得到的错误是
初始化元素不是常量

或者如果我拿掉指针指示器 (*) 我得到:
Objective-C 类 'NSArray' 的静态分配实例

Or if I take away the pointer indicator (*) I get:
statically allocated instance of Objective-C class 'NSArray'

推荐答案

简而言之,你不能.除了 NSString 之外,Objective-C 对象只能在运行时创建.因此,您不能使用表达式来初始化它们.

In short, you can't. Objective-C objects are, with the exception of NSString, only ever created at runtime. Thus, you can't use an expression to initialize them.

有几种方法.

(1) 声明 NSArray *testArray 没有 const 关键字,然后有一些代码来设置在应用程序生命周期中很早就调用的值.

(1) Declare NSArray *testArray without the const keyword and then have a bit of code that sets up the value that is invoked very early during application lifecycle.

(2) 声明一个方便的返回数组的类方法,然后在该方法中使用 static NSArray *myArray 并将其视为单例(搜索 SO for "objective-c singleton" for关于如何实例化的无数答案).

(2) Declare a convenient class method that returns the array, then use a static NSArray *myArray within that method and treat it as a singleton (search SO for "objective-c singleton" for about a zillion answers on how to instantiate).

这篇关于如何在 Objective-c 中将数组声明为常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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