How to fill NSArray in compile time?

2020-04-07 05:59发布

问题:

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.

回答1:

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.



回答2:

use this

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


回答3:

As far as i understand you need a one-dimentional array You can use class methods of NSArray.. For instance

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

If you need more, please give some more detail about your issue



回答4:

Simple as that: NSArray<NSString*> *stringsArray = @[@"Str1", @"Str2", @"Str3", ...]; Modern ObjectiveC allows generics and literal arrays.

If you want shorter code, then NSArray *stringsArray = @[@"Str1", @"Str2", @"Str3", ...];, as the generics are optional and help only when accessing the array elements, thus you can later in the code cast back to the templatized array.