forked from mrnuku/util
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathOKOMutableWeakArray.m
More file actions
99 lines (75 loc) · 2.1 KB
/
OKOMutableWeakArray.m
File metadata and controls
99 lines (75 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
//
// OKOMutableWeakArray.m
// McK.HERO.Demo
//
// Created by Kocsis Olivér on 2015. 07. 07..
// Copyright (c) 2015. Kocsis Oliver. All rights reserved.
//
#import "OKOMutableWeakArray.h"
@interface OKOMutableWeakArray ()
@property (nonatomic, strong) NSMutableArray * backingArray;
@end
@implementation OKOMutableWeakArray
#pragma mark - helpers
typedef id (^WeakReferenceInABlock)(void);
WeakReferenceInABlock wrapObjectInBlockAsWeak (id object) {
__weak id weakref = object;
return ^{ return weakref; };
}
id unwrapBlock (WeakReferenceInABlock block) {
id retObj = nil;
if (block) {
retObj = block();
}
return retObj;
}
#pragma mark - Public API
-(void) compact {
NSIndexSet * indexes = [super indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
return obj == nil;
}];
[super removeObjectsAtIndexes:indexes];
}
-(void) removeNilObjects {
[self compact];
}
#pragma mark - NSArray overrides
- (instancetype)init
{
self = [super init];
if (self) {
_backingArray = [NSMutableArray new];
}
return self;
}
-(id)objectAtIndex:(NSUInteger)index {
return unwrapBlock([_backingArray objectAtIndex:index]);
}
-(NSUInteger)count {
return [_backingArray count];
}
#pragma mark - NSMutableArray overrides
-(void)insertObject:(id)anObject atIndex:(NSUInteger)index {
[_backingArray insertObject:wrapObjectInBlockAsWeak(anObject) atIndex:index];
}
-(void)removeObjectAtIndex:(NSUInteger)index {
[_backingArray removeObjectAtIndex:index];
}
-(void)addObject:(id)anObject {
[_backingArray addObject:wrapObjectInBlockAsWeak(anObject)];
}
-(void)removeLastObject {
[_backingArray removeLastObject];
}
-(void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject {
[_backingArray replaceObjectAtIndex:index withObject:wrapObjectInBlockAsWeak(anObject)];
}
-(NSString *)description {
return [_backingArray description];
}
- (id)addObjectReturnRef:(nullable id)anObject {
id objCopy = anObject;
[_backingArray addObject:wrapObjectInBlockAsWeak(objCopy)];
return objCopy;
}
@end