我如何声明数组作为在Objective-C的常数? [英] How do I declare an array as a constant in Objective-c?
问题描述
以下code是给我的错误:
The following code is giving me errors:
// 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'
推荐答案
在短,你不能。 Objective-C的对象,用的NSString常量外,只会在运行时创建,因此,您不能使用前pression对它们进行初始化。
In short, you can't. Objective-C objects are, with the exception of NSString constants, only ever created at runtime and, thus, you can't use an expression to initialize them.
有办法了一把。
(1)声明的NSArray * testArray
没有常量
关键字,然后有位$ C $的c该设置是在应用程序生命周期调用很早的价值。
(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)宣布返回数组的便利类的方法,那么该方法中使用静态的NSArray * myArray的
,并把它作为一个单(SO为搜索Objective-C的单,了解有关如何实例化,却有无数的答案)。
(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屋!