在Objective-c中调用名称包含数字的自定义对象

时间:2016-06-12 09:53:19

标签: objective-c

我在Objective-c项目中声明了自定义对象:

Student* student1 = [[Student alloc]init];
Student* student2 = [[Student alloc]init];
Student* student3 = [[Student alloc]init];
Student* student4 = [[Student alloc]init];
Student* student5 = [[Student alloc]init];
Student* student6 = [[Student alloc]init];

如何在周期中召唤他们

for (int i=1; i<=6; i++)
{
}   ?

1 个答案:

答案 0 :(得分:3)

你不能直接这样做。你可以使用一个数组(C风格或NSArray),然后迭代它(使用从零开始的索引或for-in循环)。

例如:

NSArray* students = @[ [[Student alloc] init],
                       [[Student alloc] init],
                       [[Student alloc] init],
                       [[Student alloc] init],
                       [[Student alloc] init],
                       [[Student alloc] init],
                     ];
for (int i = 0; i < students.count; i++)
{
    Student* student = students[i];
    // Do something with student
}
// Or:
for (Student* student in students)
{
    // Do something with student
}