Multiple Objects with same name


#1

Hi everyone,

First of all this a great book for learning Objective-C but too many problems with this chapter. Up until now it has been a breeze, but this chapter is like trying to learn Quantum Physics for the first time.

Anyway, my question is how are we creating multiple objects for BNREmployee class with same name i.e., ‘mikey’. It is done inside the loop. But, how does it work, why the compiler is allowing that? Here is the code.

for (int i = 0; i < 10; i++) {
            // Create an instance of BNREmployee
            BNREmployee *mikey = [[BNREmployee alloc] init];

            // Give the instance variables interesting values
            mikey.weightInKilos = 90 + i;
            mikey.heightInMeters = 1.8 - i/10.0;
            mikey.employeeID = i;

            // Put the employee in the employees array
            [employees addObject:mikey];
        }

#2

This is a C Programming Language question, and it is a very basic one.

To make sense of what is going on, you need to know what a scope is.

A scope is a bit like a container in which you can put only uniquely named things, and from our everyday experience we know that we can put one container in another container subject to size restrictions.

Whenever the compiler sees a block of code enclosed between matching curly braces, it generates code which creates a new scope on seeing [size=150]{[/size] and destroys it on seeing the matching [size=150]}[/size].

A name defined in a scope is local to that scope, and therefore the same name can be used in different scopes.

A scope:

...
{   <-- start new scope
   ...
   FooBar *fooBar = ...
   ...
}   <-- end it

Nested scopes:

{   <-- start outer scope
   ...
   FooBar *fooBar = ...
   ...
   {   <-- start inner scope
      ...
      FooBar *fooBar = ...
      ...
   }   <-- end it
   ...
   {   <-- start inner scope
      ...
      FooBar *fooBar = ...
      ...
   }   <-- end it
   ...
}   <-- end the outer scope

[Become a competent programmer faster than you can imagine: pretty-function.org]