ios自定义迭代器

协议 Iterator

//
//  Iterator.h
//  ios_迭代器
//
//  Created by 陶亚利 on 2016/12/22.
//  Copyright © 2016年 陶亚利. All rights reserved.
//

#import 

@protocol Iterator 

@required
/*
    判断数组是否还有元素
 */
- (BOOL)hasNext;

/*
    返回数组中的元素(索引为0的元素), 必须先使用hasNext判断,否则可能出现数组越界异常
 */
- (NSObject *)next;

/*
    删除数组中的元素(索引为0的元素), 必须先使用hasNext判断,否则可能出现数组越界异常
 */
- (void)remove;

@end

分类 NSMutableArray+Helper.h

//
//  NSMutableArray+Helper.h
//  ios_迭代器
//
//  Created by 陶亚利 on 2016/12/22.
//  Copyright © 2016年 陶亚利. All rights reserved.
//

#import 
#import "Iterator.h"

@interface NSMutableArray (Helper)

/*
    返回一个迭代器
 */
- (id)iterator;

@end
//
//  NSMutableArray+Helper.m
//  ios_迭代器
//
//  Created by 陶亚利 on 2016/12/22.
//  Copyright © 2016年 陶亚利. All rights reserved.
//

#import "NSMutableArray+Helper.h"

/*
    实现私有类
 */
@interface NSMutableArrayIterator : NSObject

/**
 *   自定义初始化方法
 *     @param array 目标数组 NSMutableArray类型
 */
- (instancetype) initWithMutableArray:(NSMutableArray *) array;

/**
 *   持有的目标数组
 */
@property (nonatomic, strong) NSMutableArray *array;

@property (nonatomic, assign) int nextIndex;
@property (nonatomic, assign) int currentIndex;

@end

@implementation NSMutableArrayIterator

- (instancetype)initWithMutableArray:(NSMutableArray *)array{
    if (self = [super init]) {
        _array = array;
        _nextIndex = 0;
        _currentIndex = 0;
    }
    return self;
}

- (BOOL)hasNext{
    return _array != nil && _array.count > _currentIndex;
}

- (NSObject *)next{
    _nextIndex ++;
    _currentIndex = _nextIndex - 1;
    if (_currentIndex > (_array.count - 1)) {
        NSException *e = [NSException exceptionWithName:@"数组越界" reason:@"迭代索引错误,不能大于元素数量" userInfo:nil];
        @throw e;
    }
    
    return [_array objectAtIndex:_currentIndex];
}

- (void)remove{
    
    if (_currentIndex < 0) {
        
        NSException *e = [NSException exceptionWithName:@"状态异常" reason:@"迭代索引错误,不能小于0" userInfo:nil];
        @throw e;
    }
    [_array removeObjectAtIndex:_currentIndex];
    if (_currentIndex < _nextIndex) {
        _nextIndex --;
        _nextIndex = _nextIndex > 0 ? _nextIndex : 0;
    }
}

@end



@implementation NSMutableArray (Helper)

- (id)iterator{
    NSMutableArrayIterator *iteratorArray = [[NSMutableArrayIterator alloc] initWithMutableArray:self];
    return iteratorArray;
}

@end

使用

    NSArray *array = @[@1,@"A",@2.0f,@"B",@3,@"C",@4,@"D",@5,@"E",@6,@"F"];
    NSMutableArray *mutableItems = [NSMutableArray arrayWithArray:array];
    
    id iterator = [mutableItems iterator];
    while ([iterator hasNext]) {
        
        NSObject *object = [iterator next];
        if ([object isKindOfClass:[NSString class]]) {
            
            NSLog(@" objectValue = %@ ", object);
            [iterator remove];
        }
    }
    NSLog(@"选择删除 == %@",mutableItems);

你可能感兴趣的:(ios自定义迭代器)