2

我知道 Apple 在让您使用NS对象而不是真正的原始类型方面很重要,但我需要数组的功能(即直接访问索引处的项目)。但是,他们似乎非常热衷于使用NS对象,以至于我无法在网上或教科书中找到有关如何使用基本原始数组的教程。我想要在 Java 中做这样的事情

String inventory[] = new String[45];

inventory[5] = "Pickaxe";
inventory[12] = "Dirt";
inventory[8] = "Cobblestone";

inventory[12] = null;

System.out.println("There are " + inventory.length + " slots in inventory: " + java.util.Arrays.toString(inventory));

以下是我在 Objective-C 中得到的最接近的,但它不能正常运行:

NSString *inventory[45];

inventory[5] = @"Pickaxe";
inventory[12] = @"Dirt";
inventory[8] = @"Cobblestone";

inventory[12] = nil;

NSArray *temp = [NSArray arrayWithObjects:inventory count:45];
NSLog(@"There are %i slots in inventory: %@", [temp count], [temp description]);

另外,如果可能的话,OC中是否有一些东西可以让我计算数组中非空/非零对象的数量?(这样,我可以知道物品栏中还剩下多少空间,这样玩家就无法打包任何东西,如果它已满)

4

2 回答 2

2

使用 c 风格的数组。任何 c 代码都可以在目标 c 中工作。除非您非常小心,否则尽量不要将客观的 c 样式对象与 c 样式代码混合。内存管理的东西变得很奇怪,而且很容易混淆对象类型和原语。

于 2012-04-04T04:54:31.253 回答
2

通常,您会使用NSArray/ NSMutableArray,尽管您也可以使用 C 数组。

NSArray(和大多数 Foundation 集合)不能包含nil条目 -NSPointerArray如果需要nil值,您可以使用 (OS X),或者简单地使用[NSNull null]in anNSArray来指定nil

这是您使用的程序NSArray

NSMutableArray * inventory = [NSMutableArray array];
for (NSUInteger idx = 0; idx < 45; ++idx) {
  [inventory addObject:[NSNull null]];
}

[inventory replaceObjectAtIndex:5 withObject:@"Pickaxe"];
[inventory replaceObjectAtIndex:12 withObject:@"Dirt"];
[inventory replaceObjectAtIndex:8 withObject:@"Cobblestone"];

[inventory replaceObjectAtIndex:12 withObject:[NSNull null]];

NSArray *temp = [NSArray arrayWithObject:inventory];
NSLog(@"There are %i slots in inventory: %@", [temp count], [temp description]);

另外,如果可能的话,OC中是否有一些东西可以让我计算数组中非空/非零对象的数量?

An NSArray is a CFArray - they are "toll free bridged". Use CFArrayGetCountOfValue with [NSNull null] as the value to seek. Most of the CF-APIs are available in the NS-APIs, but not this one. You could easily wrap it in a category, if needed often.

于 2012-04-04T04:57:21.807 回答