【问题标题】:Calling custom objects whose names contain numbers in Objective-c [duplicate]在Objective-c中调用名称包含数字的自定义对象[重复]
【发布时间】:2016-06-12 09:53:19
【问题描述】:

我已经在 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++)
{
}   ?

【问题讨论】:

  • 您应该为此使用数组
  • 你不要!使用数组。

标签: objective-c


【解决方案1】:

您不能直接这样做。您可以使用一个数组(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
}

【讨论】:

    猜你喜欢
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多