Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fill NSArray in compile time?

In Objective-C, how to do something like is

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

in pure C?

I need to fill NSArray with NSStrings with the smallest overhead (code and/or runtime) as possible.

like image 915
MoreFamed Avatar asked Nov 04 '22 22:11

MoreFamed


1 Answers

It's not possible to create an array like you're doing at compile time. That's because it's 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];
}

If it's truly important that you have this precompiled, then I guess you could create a test project, create the array (or whatever object) you need, fill it, then serialize it using NSKeyedArchiver (which will save it to a file), and then include that file in your app. You will then need to use NSKeyedUnarchiver to unarchive the object for use. I'm not sure what the performance difference is between these two approaches. One advantage to this method is that you don't have a big block of code if you need to initialize an array that includes a lot of objects.

like image 76
FreeAsInBeer Avatar answered Nov 08 '22 12:11

FreeAsInBeer