How to fill NSArray in compile time?

蓝咒 提交于 2019-12-01 18:13:36

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.

use this

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

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!