Take the 2-minute tour ×

if I have a property

@property (nonatomic, retain) NSArray* myArray;

Can I do ? And if yes why does this work ?

for (id object in self.myArray)

Or do I need to do ?

NSArray* r = self.myArray;
for (id object in r)
share|improve this question
Did you try it? You could've found the answer in about 20 seconds. –  Dave DeLong Feb 10 '11 at 15:05
Actually I'm more in interested in why it works. Is it a compiler optimization ? How can the loop now that the self.myArray is always the same ? –  CodeFlakes Feb 10 '11 at 15:19

3 Answers 3

up vote 2 down vote accepted

It works because self.myArray is syntactical sugar for [self myArray], which is generated by the @synthesize keyword. So really you're doing:

for (id object in [self myArray])

And the return value of [self myArray] implements the fast enumeration protocol so the for..in syntax can work on it.

Does that make things clearer?

share|improve this answer
I see. Thanks ! –  CodeFlakes Feb 10 '11 at 16:50
I would also add that a standard read/writeable property has two functions generated by the @synthesize: myArray and setMyArray. Also this information can be found at developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/… –  Cthutu Feb 11 '11 at 20:16

Yes you can use fast enumeration like that. To answer the question from your comments, I believe that the fast enumeration protocol will throw an exception if you modify your array property during enumeration.


share|improve this answer

You can definitely go for for(id object in self.array)

share|improve this answer

Your Answer


