如何在编译时填充NSArray? [英] How to fill NSArray in compile time?

查看:106
本文介绍了如何在编译时填充NSArray?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective-C中,如何做类似的事情

In Objective-C, how to do something like is

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

在纯C语言中?

我需要用开销最小的代码(和/或运行时)最小的NSStrings填充NSArray.

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

推荐答案

无法像在编译时那样创建数组.那是因为它不是编译时间常数".相反,您可以执行以下操作:

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];
}

如果确实要进行此预编译非常重要,那么我想您可以创建一个测试项目,创建所需的数组(或任何对象),填充它,然后使用NSKeyedArchiver对其进行序列化(这会将其保存到文件中) ),然后将该文件包含在您的应用中.然后,您将需要使用NSKeyedUnarchiver来取消归档要使用的对象.我不确定这两种方法之间的性能差异是什么.这种方法的一个优点是,如果您需要初始化包含很多对象的数组,则无需编写大量代码.

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.

这篇关于如何在编译时填充NSArray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆