2

I have a NSEnumerator object with the text lines retrieved from a NSTextView, parsed with:

NSEnumerator *myLines = [[allTheText componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] objectEnumerator];

I'm processing the lines inside a for cycle like this:

for (NSString *current_line in myLines)
{
     //doing something

}

This works fine, but now I need to watch the next object while processing the current one. What would be the best way to do this without disrupting the current cycle? If I do something like this (inside the current cycle), it won't work:

//inside the previous cycle                    
NSString *next_line;

if (next_line = [myLines nextObject])
{
   //process next line
}
Eimantas
  • 48,927
  • 17
  • 132
  • 168
Miguel E
  • 1,316
  • 2
  • 17
  • 39

1 Answers1

0

You can use standard for loop:

for(uint i = 0; i < [myLines count]; i++) {
    ...
}

You'd be able to get previous and next lines be using iteration index:

[myLines objectAtIndex:(i-1)]; // previous
[myLines objectAtIndex:(i+1)]; // next

Make sure to check for their existence first.

update

NSArray *lineArray = [allTheText componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];

Use array above in the for loop.

Eimantas
  • 48,927
  • 17
  • 132
  • 168
  • But myLines is NSEnumerator (not NSArray) and it won't answer to count or objectAtIndex. I've tried before with [myLines allObjects] but the count always returns 0. Am I missing something? – Miguel E Aug 16 '11 at 13:43
  • how are you receiving the myLines variable? – Eimantas Aug 16 '11 at 13:56
  • It's written in the original post (NSEnumerator *myLines = [[allTheText componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] objectEnumerator];) – Miguel E Aug 16 '11 at 15:04
  • It seems there is not way to "peek ahead" using NSEnumerator. It's nature is just for "walking" the list until it reaches the end. I've implemented a retainer for the last object and process it in the next cycle (with delay). Thanks anyway! – Miguel E Aug 16 '11 at 15:06
  • I'm dealing with very large documents, so I believe it's a performance loss to use an array instead of the enumerator. Anyway my question was about the enumerator and with it I don't think there is a way to monitor the object ahead. – Miguel E Aug 16 '11 at 21:53
  • I'd suggest at least trying to use `NSScanner` with 2 lines scanned at one time. I think you'd gain performance boost even more. – Eimantas Aug 17 '11 at 03:19