Last active
December 12, 2016 15:16
-
-
Save CoderPiF/1db713466878d38406e68586693411ac to your computer and use it in GitHub Desktop.
给你一个嵌套的 NSArray 数据,实现一个迭代器类,该类提供一个 next() 方法,可以依次的取出这个 NSArray 中的数据。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
@interface ArrayIterator : NSObject | |
@property (nonatomic, strong) NSArray *array; | |
- (id) next; | |
- (NSArray *) allObjects; | |
@end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import "ArrayIterator.h" | |
@interface ArrayIterator () | |
@property (nonatomic, strong) NSMutableArray<NSNumber *> *status; | |
@end | |
@implementation ArrayIterator | |
- (void) setArray:(NSArray *)array | |
{ | |
if (_array == array) | |
{ | |
return; | |
} | |
_array = array; | |
_status = @[@(-1)].mutableCopy; | |
} | |
- (NSArray *) currentArray | |
{ | |
if (_status.count < 2) | |
{ | |
return _array; | |
} | |
NSArray *res = _array; | |
for (NSUInteger i = 0; i < _status.count - 1; ++i) | |
{ | |
res = res[_status[i].integerValue]; | |
} | |
return res; | |
} | |
- (id) next | |
{ | |
if (_array.count == 0) | |
{ | |
return nil; | |
} | |
NSArray *curArray = self.currentArray; | |
NSUInteger nextPos = _status.lastObject.integerValue + 1; | |
if (curArray.count > nextPos) | |
{ | |
[_status removeLastObject]; | |
[_status addObject:@(nextPos)]; | |
id res = curArray[nextPos]; | |
if ([res isKindOfClass:[NSArray class]]) | |
{ | |
[_status addObject:@(-1)]; | |
return [self next]; | |
} | |
return res; | |
} | |
if (curArray != _array) | |
{ | |
[_status removeLastObject]; | |
return [self next]; | |
} | |
return nil; | |
} | |
+ (void) dfsArray:(NSArray *)targetArray result:(NSMutableArray *)resArray | |
{ | |
if (targetArray.count == 0) | |
{ | |
return; | |
} | |
for (id item in targetArray) | |
{ | |
if ([item isKindOfClass:[NSArray class]]) | |
{ | |
[self dfsArray:item result:resArray]; | |
} | |
else | |
{ | |
[resArray addObject:item]; | |
} | |
} | |
} | |
- (NSArray *) allObjects | |
{ | |
NSMutableArray *res = @[].mutableCopy; | |
[ArrayIterator dfsArray:_array result:res]; | |
return res; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment