Ulugbek Aytbaev Ulugbek Aytbaev - 5 months ago 8
iOS Question

Calling custom objects whose names contain numbers in Objective-c

I have declared custom objects in Objective-c project:

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



How can I call them in cycle


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

} ?

Answer

You can't directly do that. You could use an array (either C-style or an NSArray) and then iterate over that (using zero-based indexes or a for-in loop).

For example:

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
}