1. 实现思路
- 首先定义一个协议,用于规定迭代器的基本行为,例如获取下一个元素,判断是否还有下一个元素。
- 接着创建一个自定义数组类,该类包含数组数据以及创建迭代器的方法。
- 然后实现迭代器类,该类遵循之前定义的协议,持有自定义数组类的实例,并实现协议中的方法来遍历数组。
2. 代码实现
// 定义迭代器协议
@protocol IteratorProtocol <NSObject>
- (BOOL)hasNext;
- (id)next;
@end
// 自定义数组类
@interface MyArray : NSObject
@property (nonatomic, strong) NSMutableArray *array;
- (id<IteratorProtocol>)createIterator;
@end
@implementation MyArray
- (id<IteratorProtocol>)createIterator {
return [[MyArrayIterator alloc] initWithArray:self.array];
}
@end
// 迭代器类
@interface MyArrayIterator : NSObject <IteratorProtocol>
@property (nonatomic, strong) NSMutableArray *array;
@property (nonatomic, NSInteger) index;
- (instancetype)initWithArray:(NSMutableArray *)array;
@end
@implementation MyArrayIterator
- (instancetype)initWithArray:(NSMutableArray *)array {
self = [super init];
if (self) {
self.array = array;
self.index = 0;
}
return self;
}
- (BOOL)hasNext {
return self.index < self.array.count;
}
- (id)next {
if ([self hasNext]) {
id object = self.array[self.index];
self.index++;
return object;
}
return nil;
}
@end
3. 使用示例
int main(int argc, const char * argv[]) {
@autoreleasepool {
MyArray *myArray = [[MyArray alloc] init];
myArray.array = [NSMutableArray arrayWithObjects:@"one", @"two", @"three", nil];
id<IteratorProtocol> iterator = [myArray createIterator];
while ([iterator hasNext]) {
NSLog(@"%@", [iterator next]);
}
}
return 0;
}