How to populate NSArray at compile time?

In Objective-C, how to do something like

int array[] = {1, 2, 3, 4};

in pure C?

I need to populate an NSArray using NSStrings with the least cost (code and / or runtime) as much as possible.

+5
source share
4 answers

It is not possible to create an array that you make at compile time. This is because it is not a “compile-time constant”. Instead, you can do something like:

static NSArray *tArray = nil;

-(void)viewDidLoad {
    [super viewDidLoad];

    tArray = [NSArray arrayWithObjects:@"A", @"B", @"C", nil];
}

, , , , ( ), , , NSKeyedArchiver ( ), . NSKeyedUnarchiver . , . , , , .

+7

NSArray *array = [NSArray arrayWithObjects:str1,str2,  nil];
-1

, NSArray.

NSString *yourString;
NSArray  *yourArray = [[NSArray alloc] initWithObjects:yourString, nil];

, .

-2

Simple: NSArray<NSString*> *stringsArray = @[@"Str1", @"Str2", @"Str3", ...];Modern ObjectiveC allows you to create generics and literals.

If you need a shorter code, then NSArray *stringsArray = @[@"Str1", @"Str2", @"Str3", ...];, since the general parameters are optional and only help when accessing the elements of the array, you can later include the code in a template array.

-2
source

All Articles