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

查看:22
本文介绍了如何在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]];
}

或者,使用数组字面量,您可以获得一个不可变版本,如下所示:

Or, using array literals, you can get an immutable version like this:

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

然后像这样使用它:

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

另一个区别是您可以将 nil 放入 C 样式数组,但不能放入 NSArrays - 为此您需要使用 NSNull.另请查看堆栈溢出问题 Cocoa:使用 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天全站免登陆