在Objective-C中使用许多整数

时间:2012-01-12 03:29:16

标签: objective-c integer

我是编程新手,我从大学开始有一些基本的python编程,我熟悉一些OOP基础知识,并希望在管理大量整数方面提供一些帮助。我有88个。 7将用于捕获用户输入,而其他81将用于特定计算。而不是编写以下代码:

int currentPlace;
int futurePlace;
int speed;
int distance;

int place1 = 1;
int place2 = 2;
int place3 = 3;
// etc...
int place81 = 81;

然后回到整数并询问用户定义的问题,例如:

NSLog(@"What place is the runner in?");
scanf("%i", &currentPlace);
NSLog(@"What place does the runner finish in?");
scanf("%i", &futurePlace);
NSLog(@"What is the distance of the track?");

// doing some math

NSLog(@"The runner is running at "i" MPH.",speed);

我记得有一种更简单的方法来使用整数,但我一直在想enum或typedef。

我希望用户选择一个数字而不必运行一个巨大的if语句来完成工作以尽可能地减少程序的大小。

这是我的第一个“on my own”应用程序,所以任何有用的指针都会很棒。

感谢。

2 个答案:

答案 0 :(得分:1)

你在想C阵列吗?

int myPlaces[81];
for (int i=0; i<81; i++) {
    myPlaces[i] = 0;
}

答案 1 :(得分:1)

我还不明白为什么你需要所有这些place,但我也假设数组在这里更容易使用。您可以使用NSArrayNSMutableArray。它们之间的区别在于,与NSArray不同,NSMutableArray实例在创建后无法更改(您无法添加/删除元素)。

使用NSArray

NSArray *places = [NSArray arrayWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2],[NSNumber numberWithInt:3], ..., [NSNumber numberWithInt:81],  nil];
最后的

nil表示数组内容的结束。 [NSNumber numberWithInt:1]返回一个作为参数给出的int(我们不能直接给数组赋一个int,因为数组需要一个对象作为参数。

您可以使用以下方式访问数组的内容:

[places objectAtIndex:(NSUInteger)];

记住一个数组从0开始计数,所以如果你想获得5,你必须这样做

[places objectAtIndex:4];

使用NSMutableArray

我建议您使用此选项。

在这里使用for会更容易。

NSMutableArray *places = [NSMutableArray array];
for (int i = 1; i < 81; i++)
{
    [places addObject:[NSNumber numberWithInt:i]];
}

然后您可以像在NSArray中一样访问数据:

[places objectAtIndex:0];

这将返回1.你可以用0开始for - 循环。之后,数组的索引将对应于里面的整数,所以

[places objectAtIndex:5];

实际上会返回5.