Created
October 9, 2015 04:38
-
-
Save khanlou/26288ec9854f366081bf to your computer and use it in GitHub Desktop.
This file contains 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
@interface MappedArraySentinel : NSObject @end | |
@implementation MappedArraySentinel @end | |
@interface LazyMappedArray () | |
@property (nonatomic) NSArray *originalArray; | |
@property (nonatomic) NSMutableArray *backingArray; | |
@property (nonatomic, copy) id (^block)(id); | |
@end | |
@implementation LazyMappedArray | |
- (instancetype)initWithArray:(NSArray *)array transformationBlock:(id (^)(id object))block { | |
self = [super init]; | |
if (!self) return nil; | |
_originalArray = array; | |
_block = [block copy]; | |
return self; | |
} | |
- (NSMutableArray *)backingArray { | |
if (!_backingArray) { | |
NSMutableArray *mappedArray = [NSMutableArray arrayWithCapacity:self.originalArray.count]; | |
for (NSInteger i = 0; i < self.originalArray.count; i++) { | |
[mappedArray addObject:[MappedArraySentinel new]]; | |
} | |
self.backingArray = mappedArray; | |
} | |
return _backingArray; | |
} | |
- (NSUInteger)count { | |
return self.backingArray.count; | |
} | |
- (id)objectAtIndex:(NSUInteger)index { | |
if ([[self.backingArray objectAtIndex:index] isKindOfClass:[MappedArraySentinel class]]) { | |
[self.backingArray replaceObjectAtIndex:index withObject:self.block(self.originalArray[index]) ?: [NSNull null]]; | |
} | |
return [self.backingArray objectAtIndex:index]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is there a bug? If customs call
- initWithArray:transformationBlock:
with an array of typeNSMutableArray
, and modify that array immediately, later call methods onLazyMappedArray
object, he may get unexpected result.