Skip to content

Instantly share code, notes, and snippets.

@NathanLi NathanLi/Iterator.h
Last active Dec 13, 2016

Embed
What would you like to do?
给你一个嵌套的 NSArray 数据,实现一个迭代器类,该类提供一个 next() 方法,可以依次的取出这个 NSArray 中的数据。 比如 NSArray 如果是 [1,[4,3],6,[5,[1,0]]], 则最终应该输出:1, 4, 3, 6, 5, 1, 0 。 另外,实现一个 allObjects 方法,可以一次性取出所有元素。 Raw
#import <Foundation/Foundation.h>
@protocol Collection;
@protocol Iterator <NSObject>
- (id _Nullable)next;
- (NSArray *_Nonnull)allObjects;
@end
@protocol Collection <NSObject>
- (id<Iterator> _Nonnull)iterator;
@end
#import <Foundation/Foundation.h>
#import "Iterator.h"
@interface NSArray (Iterator) <Collection>
@end
#import "NSArray+Iterator.h"
@interface NSArrayIterator : NSObject<Iterator>
@property (nonatomic, strong) NSArray *array;
@property (nonatomic, assign) NSUInteger index;
@property (nonatomic, strong) id<Iterator> iteratorOfElement;
- (instancetype)initWithArray:(NSArray *)array;
@end
@implementation NSArrayIterator
- (id)next {
id nextOfElement = [self nextOfElement];
if (nextOfElement) {
return nextOfElement;
}
if (self.array.count <= self.index) {
return nil;
}
id next = [self.array objectAtIndex:self.index++];
if ([next respondsToSelector:@selector(iterator)]) {
self.iteratorOfElement = [next iterator];
next = [self next];
}
while (next == nil && self.array.count < self.index) {
next = [self next];
}
return next;
}
- (id)nextOfElement {
if (self.iteratorOfElement) {
id next = [self.iteratorOfElement next];
if (next == nil) {
self.iteratorOfElement = nil;
}
return next;
}
return nil;
}
- (NSArray *)allObjects {
NSMutableArray *objects = [NSMutableArray array];
id<Iterator> iterator = [self.array iterator];
id next = [iterator next];
while (next) {
[objects addObject:next];
next = [iterator next];
}
return objects;
}
- (instancetype)initWithArray:(NSArray *)array {
if (self = [super init]) {
_array = [array copy];
}
return self;
}
@end
@implementation NSArray (Iterator)
- (id<Iterator>)iterator {
return [[NSArrayIterator alloc] initWithArray:self];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.