協(xié)議 Iterator
//
// Iterator.h
// ios_迭代器
//
// Created by 陶亞利 on 2016/12/22.
// Copyright ? 2016年 陶亞利. All rights reserved.
//
#import <Foundation/Foundation.h>
@protocol Iterator <NSObject>
@required
/*
判斷數(shù)組是否還有元素
*/
- (BOOL)hasNext;
/*
返回數(shù)組中的元素(索引為0的元素)左冬, 必須先使用hasNext判斷冗锁,否則可能出現(xiàn)數(shù)組越界異常
*/
- (NSObject *)next;
/*
刪除數(shù)組中的元素(索引為0的元素), 必須先使用hasNext判斷焕议,否則可能出現(xiàn)數(shù)組越界異常
*/
- (void)remove;
@end
分類 NSMutableArray+Helper.h
//
// NSMutableArray+Helper.h
// ios_迭代器
//
// Created by 陶亞利 on 2016/12/22.
// Copyright ? 2016年 陶亞利. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Iterator.h"
@interface NSMutableArray (Helper)
/*
返回一個迭代器
*/
- (id<Iterator>)iterator;
@end
//
// NSMutableArray+Helper.m
// ios_迭代器
//
// Created by 陶亞利 on 2016/12/22.
// Copyright ? 2016年 陶亞利. All rights reserved.
//
#import "NSMutableArray+Helper.h"
/*
實現(xiàn)私有類
*/
@interface NSMutableArrayIterator : NSObject<Iterator>
/**
* 自定義初始化方法
* @param array 目標數(shù)組 NSMutableArray類型
*/
- (instancetype) initWithMutableArray:(NSMutableArray *) array;
/**
* 持有的目標數(shù)組
*/
@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:@"數(shù)組越界" reason:@"迭代索引錯誤诵棵,不能大于元素數(shù)量" userInfo:nil];
@throw e;
}
return [_array objectAtIndex:_currentIndex];
}
- (void)remove{
if (_currentIndex < 0) {
NSException *e = [NSException exceptionWithName:@"狀態(tài)異常" reason:@"迭代索引錯誤舶胀,不能小于0" userInfo:nil];
@throw e;
}
[_array removeObjectAtIndex:_currentIndex];
if (_currentIndex < _nextIndex) {
_nextIndex --;
_nextIndex = _nextIndex > 0 ? _nextIndex : 0;
}
}
@end
@implementation NSMutableArray (Helper)
- (id<Iterator,NSObject>)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> iterator = [mutableItems iterator];
while ([iterator hasNext]) {
NSObject *object = [iterator next];
if ([object isKindOfClass:[NSString class]]) {
NSLog(@" objectValue = %@ ", object);
[iterator remove];
}
}
NSLog(@"選擇刪除 == %@",mutableItems);
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者