如何在 Objective-c 中将数组声明为常量?

发布于 2024-08-25 07:57:28 字数 332 浏览 5 评论 0原文

以下代码给了我错误:

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

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

或者,如果我拿走指针指示符 (*),我会得到:
Objective-C 类“NSArray”的静态分配实例

The following code is giving me errors:

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

The error I get is
initializer element is not constant

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

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

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

发布评论

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

评论(6

像极了他 2024-09-01 07:57:28

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

有几种方法。

(1) 声明不带 const 关键字的 NSArray *testArray,然后使用一些代码来设置在应用程序生命周期早期调用的值。

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

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.

There are a handful of approaches.

(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) 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).

挽袖吟 2024-09-01 07:57:28

有点晚了,但由于您在程序过程中没有更改值,如果您只处理字符串,则可以通过使用 C 声明数组来执行以下操作数组:

extern NSString * const MY_CONSTANT_STRING_ARRAY[];

在您的 constants.h 文件中,然后在您的 constants.m 文件中,您可以向其中添加对象,如下所示:

NSString * const MY_CONSTANT_STRING_ARRAY[] = { @"foo", @"bar" };

然后要访问成员,您可以使用 C sizeof() 运算符执行 for 循环:

这显然是一个 C 数组,而不是 >NSArray 这样你就不会像 objectAtIndex: 这样附加到它上面的所有有趣方法,所以你可以在程序中的某个地方创建一个辅助函数,使用它循环遍历所有字符串我上面概述的方法并返回一个 NSArray (甚至是 NSMutableArray)。但是,如果您正在做我所做的事情并且只需要在整个程序中使用一个 NSString 值的常量数组,那么此方法效果最好。

这样做会将所有字符串数组常量封装在 constants.h 中,并且通过在 .pch< 中添加 constants.h 仍然可以在整个程序中使用。 /code> 文件,而不是仅仅为这个值数组创建一个单例或用一些代码设置该数组,这有点违背了 constants 文件的目的,因为它从 中删除了实际的常量。 code>constants 文件..

根据 @JesseGumpo 的评论进行编辑

由于使用 sizeof() 确定数组的大小可能存在问题,一个简单的方法解决方法是在常量文件中声明数组的大小,如下所示:

//.h
extern int SIZE_OF_MY_CONSTANTS_ARRAY;  

///.m
int SIZE_OF_MY_CONSTANTS_ARRAY = 2;

然后要访问 for 循环中的成员,可以这样做:

for (int i=0; i < SIZE_OF_MY_CONSTANTS_ARRAY; i++) 
        NSLog(@"my constant string is: %@", MY_CONSTANT_STRING_ARRAY[i]);

是的,这不会动态捕获数组的大小,但如果您在常量文件中声明一个数组时,您从一开始就知道该数组的大小,因此即使它添加了两行代码,它仍然完成了在常量文件中包含数组的任务。

如果有人有更多建议或可能知道其他一些 C 技巧,请在下面发表评论!

A little late to the party, but since you're not changing the values through the course of the program, if you were only dealing with strings, you could do the following by declaring your array using a C array:

extern NSString * const MY_CONSTANT_STRING_ARRAY[];

in your constants.h file, and then in your constants.m you could add objects to it like so:

NSString * const MY_CONSTANT_STRING_ARRAY[] = { @"foo", @"bar" };

Then to access a member, you could do a for loop like so with a C sizeof() operator:

This obviously is a C array and not a NSArray so you don't get all of the fun methods attached to it like objectAtIndex:, so you could create a helper function somewhere in your program that loops through all of the strings using the method I outlined above and returns an NSArray (or NSMutableArray even). But, if you were doing what I am and just need a constant array of NSString values to use throughout your program, this method works the best.

Doing it this way encapsulates all of your string array contants in constants.h, and is still available throughout your program by adding constants.h in your .pch file instead of creating a singleton just for this array of values or setting the array with a little code, which sorta defeats the purpose of a constants file because it removes the actual constants out of the constants file..

EDIT per @JesseGumpo's Comment:

Since there may be issues with using sizeof() to determine the size of the array, a simple workaround is to declare the size of the array in your constants file like so:

//.h
extern int SIZE_OF_MY_CONSTANTS_ARRAY;  

///.m
int SIZE_OF_MY_CONSTANTS_ARRAY = 2;

And then to access the members in a for loop you can do so like this:

for (int i=0; i < SIZE_OF_MY_CONSTANTS_ARRAY; i++) 
        NSLog(@"my constant string is: %@", MY_CONSTANT_STRING_ARRAY[i]);

Yes, this doesn't dynamically capture the size of the array, but if you're declaring an array in a constants file you already know the size of that array from the start, so even though it adds two more lines of code, it still accomplishes the task of having an array in a constants file.

If anyone has any more suggestions or may know some other C tricks please leave a comment below!

落墨 2024-09-01 07:57:28

下面是一个宏,用于在方法范围内的静态实例的一行中执行此操作。

#define STATIC_ARRAY(x, ...)   \
        static NSArray* x=nil; \
        static dispatch_once_t x##onceToken; \
        dispatch_once(&x##onceToken, ^{ x = @[ __VA_ARGS__ ]; });

使用示例

    STATIC_ARRAY(foo, @"thing1", @"thing2", [NSObject new]);

Here's a macro to do it in one line for a static instance in a method scope.

#define STATIC_ARRAY(x, ...)   \
        static NSArray* x=nil; \
        static dispatch_once_t x##onceToken; \
        dispatch_once(&x##onceToken, ^{ x = @[ __VA_ARGS__ ]; });

Use example

    STATIC_ARRAY(foo, @"thing1", @"thing2", [NSObject new]);
夜访吸血鬼 2024-09-01 07:57:28

这非常简单:

#define arrayTitle [NSArray arrayWithObjects: @"hi",@"foo",nil]

放在实现之前并且不带分号。

希望有帮助。

It's pretty easy :

#define arrayTitle [NSArray arrayWithObjects: @"hi",@"foo",nil]

put before implementation and without semicolon.

hope it helps.

蹲在坟头点根烟 2024-09-01 07:57:28

对于我来说,对常量数组使用以下实现更方便

static NSString * kHeaderTitles [3] = {@ "ACCOUNT DETAILS", @ "SOCIAL NETWORK", @ "SETTINGS"};
static int kNumbers[3] = {1, 2, 3};

As for me, it is more convenient to use the following implementation for an array of constants

static NSString * kHeaderTitles [3] = {@ "ACCOUNT DETAILS", @ "SOCIAL NETWORK", @ "SETTINGS"};
static int kNumbers[3] = {1, 2, 3};
浅暮の光 2024-09-01 07:57:28

我有一个名为“Constants.h”的头文件,在下一个常量数组中:

#define arrayOfStrings @[@"1", @"2", @"3", @"4"]
#define arraysOfIds @[@(1), @(2), @(3), @(4)]

基本上,当您在代码中调用 arrayOfStrings 时,会被替换为 @[@"1", @"2", @"3", @" 4"] 与 arraysOfIds 相同。

I have a header file called "Constants.h" and within the next constant arrays:

#define arrayOfStrings @[@"1", @"2", @"3", @"4"]
#define arraysOfIds @[@(1), @(2), @(3), @(4)]

Basically, when you call arrayOfStrings in your code, is replaced with @[@"1", @"2", @"3", @"4"] and the same thing with arraysOfIds.

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