Lottery nsnumber in array


In the code for creating the lottery loop

    for (i = 0; i < 10; i++) {
        NSNumber * newNumber = [[NSNumber alloc] initWithInt:(i * 3)];
        [array addObject:newNumber];

Aren’t you creating the same variable 10 times over? How does it know that it’s a different NSNumber, or a pointer to a different number? Does the alloc & init create a new pointer every time even though the name of the variable never changes?

Outside of the loop, if I try to declare

    NSNumber * newNumber = [[NSNumber alloc] initWithInt:(1 * 3)];
    NSNumber * newNumber = [[NSNumber alloc] initWithInt:(2 * 3)];

the compiler complains about a "Redifinition of ‘newNumber.’ How is it that this works inside of a loop?

– jmca


In the loop the newNumber is only a temporary variable which stores only the pointer to the part of the memory where your created numbers lie.
And then with [array addObject:newNumber] you store every pointer (NSNumber object/instance) in the array instance. In the next step newNumber stores a new pointer.
You have to understand that you not always create an new variable named newNumber, but you reserve a new part of the memory to store your numbers - newNumber is just a name to access the memory pointer. You have to remember that Objective-C works with objects and pointers.
In your own example you overwrite the first memory pointer - so you will never be able to access your “3” again --> memory leak and thats why the compiler complains.