Re: NSEnumerator and the missing peek method
Re: NSEnumerator and the missing peek method
- Subject: Re: NSEnumerator and the missing peek method
- From: Greg Parker <email@hidden>
- Date: Thu, 29 Sep 2005 16:59:06 -0700
Jan Vereecken wrote:
I'm currently busy with a project where I regularly make use of a
NSEnumerator object to iterate over a set of objects. The "problem"
I'm experiencing is that there is no method to peek at the next
object (for example [enumerator hasNext]). I circumvent the need to
peek via the enumerator with counting the objects of the enumerator
([[enumerator allObjects] count]) and check when the last element
is reached (and do something).
You could write a wrapper class that can peek ahead using the
enumerator's -nextObject but then stores it for later non-peeking
use. Something like the following UNTESTED code (allocation and
deallocation left as an exercise for the reader):
@interface PeekingEnumerator : NSObject {
NSEnumerator *enumerator;
id peek;
}
-(id) nextObject;
-(id) peekObject;
-(BOOL) hasNext;
@end
@implementation
-(id) nextObject {
if (peek) {
id result = [peek autorelease];
peek = nil;
return result;
} else {
return [enumerator nextObject];
}
}
-(id) peekObject {
if (peek) return peek;
else return peek = [[enumerator nextObject] retain];
}
-(BOOL) hasNext {
return [self peekObject] ? YES : NO;
}
@end
--
Greg Parker email@hidden
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden