array of strings in a constant with #define - objective c

ios, objective-c

Solution

I don't think you want to use `#define` for this.

In your example, there is no constant array of strings made with this code. Every single time `rows` is used in your code, a new NSArray is going to be allocated. Also, `KEY_ROWA` refers to columnas, but that isn't in the rows define. I assume you have something like this

NSArray *columnas = rows;

There is really no difference between that and

NSArray *columnas = [NSArray arrayWithObjects: @"NameRowA",@"NameRowB",@"NameRowC", nil];

But the second line is a lot more obvious. The same is true with `KEY_ROWA` -- the objectAtIndex call would be more obvious and the macro doesn't get you anything.

I'm not sure what you need exactly, but if you need a shared constant array of strings inside of one class, you could declare it as `+` instead of `-` at the beginning, and allocate it once (this is a class variable as opposed to an instance variable). More info here:

How do I declare class-level properties in Objective-C?

Problem

I need a array of strings in a constant. is a good idea to use #define? For example: ``` #define rows [NSArray arrayWithObjects: @"NameRowA",@"NameRowB",@"NameRowC", nil] #define KEY_ROWA [columnas objectAtIndex:0] #define KEY_ROWB [columnas objectAtIndex:1] #define KEY_ROWC [columnas objectAtIndex:2] ``` I need to access to the array of strings and the elements of that array. I have read, (i don´t know if is true) with this way it is created a new NSArray when it is used, I suppose then the array is released, so I think this is good because you only use that part of memory when you need it.

Original source

Related problems