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

I am just learning objective-C and I wonder why the following code leads to an error?

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

In this case, the second line gives an error indicating that the pointer "p" is already defined.

It makes sense to me; however, if it is true that the pointer cannot be redefined, then why does the following code work?

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

When I inject this into Xcode, it gives no errors, and it compiles and works just fine. In this case, I would expect the loop to simply override the p pointer, similar to how they will be declared sequentially, but this is not the case.

Does anyone have an explanation why this is?

+5
source share
2 answers
 Person *p = [[Person alloc] init]; Person *p = [[Person alloc] init]; 

In the first case, two p in the same local area, they are all local variables, so they have the same priority. We cannot have two variables with the same name and the same priority.

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

The above case will be approved because the second p has a higher priority in its local area than the first p .

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

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

+5
source

In a nutshell, this is due to the fact that in the case of a for loop, the variable p is local to the loop itself, so at the end of each iteration p and any other variables local to the loop region only are freed.

+1
source

Source: https://habr.com/ru/post/1203105/


All Articles