如何申报在Objective-C字符串类型的二维数组? [英] How to declare a two dimensional array of string type in Objective-C?

查看:194
本文介绍了如何申报在Objective-C字符串类型的二维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何申报在Objective-C字符串类型的二维数组?

How do I declare a two dimensional array of string type in Objective-C?

推荐答案

首先,你可以考虑使用一个类来保存你的内心阵列的字符串,或从plist文件(其中就很容易加载它使一个二维数组的字符串)。

First, you might consider using a class to hold your inner array's strings, or loading it from a plist file (in which it is easy to make an 2d array of strings).

有关直接声明,你有两个选择。如果你想使用一个NSArray,你必须手动创建的结构是这样的:

For direct declarations, you have a couple of options. If you want to use an NSArray, you'll have to manually create the structure like this:

NSMutableArray *strings = [NSMutableArray array];
for(int i = 0; i < DESIRED_MAJOR_SIZE; i++)
{
    [strings addObject: [NSMutableArray arrayWithObject:@"" count:DESIRED_MINOR_SIZE]];
}

或者,使用数组文本,你可以得到一个的一成不变的版本是这样的:

NSArray *strings = @[ @[ @"A", @"B", @"C" ], @[ @"D", @"E", @"F" ], @[ @"G", @"H", @"I" ] ]

然后就可以使用这样的:

You can then use it like this:

NSString *s = [[strings objectAtIndex:i] objectAtIndex:j];

这是有点尴尬初始化,但它去,如果你想使用NSArray的方法的方式。

This is somewhat awkward to initialize, but it is the way to go if you want to use the NSArray methods.

另一种方法是使用C数组:

An alternative is to use C arrays:

NSString *strings[MAJOR_SIZE][MINOR_SIZE] = {0}; // all start as nil

,然后用它是这样的:

And then use it like this:

NSString *s = strings[i][j];

这是不太尴尬,但你必须要小心的保留/复制的和的发布的价值观,你把他们和从阵列中删除。 (!除非你使用ARC,当然)的NSArray会为你而用C风格的数组做到这一点,你需要做这样的事情,以取代一个数组:

This is less awkward, but you have to be careful to retain/copy and release values as you put them in to and remove them from the array. (Unless you're using ARC, of course!) NSArray would do this for you but with C-style arrays, you need to do something like this to replace an array:

[strings[i][j] release];
strings[i][j] = [newString retain];

另外一个区别是,你可以把零的C风格的数组中,而不是NSArrays - 你需要使用NSNull了点。也看看堆栈溢出问题的 可可:内存管理使用的NSString 的所有关于NSString的内存管理。

The other difference is that you can put nil in the C-style array, but not the NSArrays - you need to use NSNull for that. Also take a look at Stack Overflow question Cocoa: Memory management with NSString for more about NSString memory management.

这篇关于如何申报在Objective-C字符串类型的二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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