Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can duplicate objective-C objects be declared in a loop, but not in sequence?

I am just learning objective-C, and am wondering why the following code results in an error?

Person *p = [[Person alloc] init];
Person *p = [[Person alloc] init];

In this case, the second line gives an error stating the "p" pointer has already been defined.

This makes sense to me; however, if it is true that a pointer cannot be re-defined, then why does the following code work?

for(int i = 0; i<10; i+=1) {
    Person *p = [[Person alloc] init];
}

When I enter this in XCode it does not give any errors, and it compiles and runs just fine. In this case, I'd expect the loop to simply re-define the "p" pointer, similar to having them be declared sequentially, but this is not the case.

Does anyone have an explanation for why this is?

like image 893
Topher Avatar asked Sep 22 '14 02:09

Topher


2 Answers

Person *p = [[Person alloc] init];
Person *p = [[Person alloc] init];

In the first case, two p in the same local scope, they are all local variables, so they have the same priority. We can't have two variable with the same name and the same priority.

Person *p = [[Person alloc] init];
{
    Person *p = [[Person alloc] init];
}

The above case will be ok because the second p has higher priority in its local scope than the first p.

for(int i = 0; i<10; i+=1) {
    Person *p = [[Person alloc] init];
}

In the second case, all the p are in different local scopes.

like image 125
KudoCC Avatar answered Nov 15 '22 05:11

KudoCC


In a nutshell, it is because in the case of the for-loop the variable p is local to the loop itself, so at the end of each iteration p and any other variables local only to the loop's scope is deallocated.

like image 21
Mike Avatar answered Nov 15 '22 03:11

Mike