0

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)
    ;
CodeFlakes
  • 3,671
  • 3
  • 25
  • 28

3 Answers3

2

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?

Cthutu
  • 8,713
  • 7
  • 33
  • 49
  • 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 http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocProperties.html – Cthutu Feb 11 '11 at 20:16
1

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.

http://www.mikeash.com/pyblog/friday-qa-2010-04-16-implementing-fast-enumeration.html

kubi
  • 48,104
  • 19
  • 94
  • 118
0

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

iHS
  • 5,372
  • 4
  • 31
  • 49