-
Notifications
You must be signed in to change notification settings - Fork 4
/
NSArray+Dejal.m
676 lines (509 loc) · 19.1 KB
/
NSArray+Dejal.m
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
//
// NSArray+Dejal.m
// Dejal Open Source Categories
//
// Created by David Sinclair on Fri May 30 2003.
// Copyright (c) 2003-2015 Dejal Systems, LLC. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#import "NSArray+Dejal.h"
#import "NSObject+Dejal.h"
@implementation NSArray (Dejal)
/**
Returns YES if the index is in the acceptable range for the receiver, or NO if not. If using the index with -objectAtIndex: or similar when this returns NO, you'll get an exception.
@author DJS 2003-11.
*/
- (BOOL)dejal_isValidIndex:(NSUInteger)i
{
return (i < [self count]);
}
// See <http://www.macdevcenter.com/pub/a/mac/2004/07/16/hom.html> for an interesting technique to do something similar to the following methods.
/**
Returns the first dictionary object where the value for the specified key is equivalent to the match value (see -isEquivalentTo:), or nil if none do. Useful for the common pattern of finding an object based on a dictionary value. See also -indexOfObjectMatching:usingKey:, -objectMatching:usingSelector:, and -arrayWithObjectsMatching:usingKey:, below.
@author DJS 2004-04.
@version DJS 2014-09: changed to use block enumeration instead of NSEnumerator.
*/
- (id)dejal_objectMatching:(id)match usingKey:(NSString *)key;
{
__block id foundObject = nil;
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
if ([obj respondsToSelector:@selector(objectForKey:)] && [obj[key] dejal_isEquivalentTo:match])
{
foundObject = obj;
*stop = YES;
}
}];
return foundObject;
}
/**
Returns the index of the first dictionary object where the value for the specified key is equivalent to the match value (see -isEquivalentTo:), or NSNotFound if none do. Useful for the common pattern of finding the index of an object based on a dictionary value. See also -objectMatching:usingKey:, above, and -arrayWithObjectsMatching:usingKey:, below.
@author DJS 2004-04.
@version DJS 2014-09: changed to use block enumeration instead of NSEnumerator.
*/
- (NSUInteger)dejal_indexOfObjectMatching:(id)match usingKey:(NSString *)key
{
return [self indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop)
{
return [obj respondsToSelector:@selector(objectForKey:)] && [obj[key] dejal_isEquivalentTo:match];
}];
}
/**
Returns the first object where the specified selector's return value is equivalent to the match value (see -isEquivalentTo:), or nil if none do. Useful for the common pattern of finding an object based on an accessor value. See also arrayWithObjectsMatching:usingSelector:, below.
@author DJS 2004-02.
@version DJS 2014-09: changed to use block enumeration instead of NSEnumerator.
*/
- (id)dejal_objectMatching:(id)match usingSelector:(SEL)selector;
{
__block id foundObject = nil;
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
if ([[obj performSelector:selector] dejal_isEquivalentTo:match])
{
foundObject = obj;
*stop = YES;
}
}];
return foundObject;
}
/**
Returns the first object where the specified selector's return value is equivalent to the match value (see -isEquivalentTo:). If none do, but a default match value was specified and an object matching that was found, it is returned instead. If not, but firstIfNotFound is YES, the first object is returned. Otherwise nil is returned. Useful for the common pattern of finding an object based on an accessor value, and handling default cases. See also objectMatching:usingSelector:, above.
@author DJS 2004-06.
@version DJS 2014-09: changed to use block enumeration instead of NSEnumerator.
*/
- (id)dejal_objectMatching:(id)match orDefault:(id)defaultMatch orFirst:(BOOL)firstIfNotFound usingSelector:(SEL)selector
{
if (!match && !defaultMatch && !firstIfNotFound)
{
// Short-circuit:
return nil;
}
__block id foundObject = nil;
__block id defaultObject = nil;
__block id firstObject = nil;
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
id result = [obj performSelector:selector];
// Is it the one we want?
if ([result dejal_isEquivalentTo:match])
{
foundObject = obj;
*stop = YES;
}
// Is a default match specified, and is it that one?
if (defaultMatch && [result dejal_isEquivalentTo:defaultMatch])
{
defaultObject = obj;
}
// Have we not noted the first one yet, and do we care?
if (!firstObject && firstIfNotFound)
{
firstObject = obj;
}
}];
if (foundObject)
{
return foundObject;
}
else if (defaultObject)
{
return defaultObject;
}
else if (firstObject)
{
return firstObject;
}
return nil;
}
/**
Returns a new array of all objects that respond to -objectForKey: and that method's return value is equivalent to the match value (see -isEquivalentTo:). If none do, an empty array is returned. Useful for the common pattern of finding objects in an array of dictionaries. See also -objectMatching:usingKey: and -arrayWithObjectsMatching:usingSelector:, above.
@author DJS 2005-03.
@version DJS 2014-09: changed to use block enumeration instead of NSEnumerator.
*/
- (NSArray *)dejal_arrayWithObjectsMatching:(id)match usingKey:(NSString *)key
{
__block NSMutableArray *array = [NSMutableArray array];
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
if ([obj respondsToSelector:@selector(objectForKey:)] && [obj[key] dejal_isEquivalentTo:match])
{
[array addObject:obj];
}
}];
return array;
}
/**
Returns a new array of all objects where the specified selector's return value is equivalent to the match value (see -isEquivalentTo:). If none do, an empty array is returned. Useful for the common pattern of finding objects based on an accessor value. See also -objectMatching:usingSelector:, above, and -arrayWithObjectsMatching:usingKey:, below.
@author DJS 2004-02.
@version DJS 2014-09: changed to use block enumeration instead of NSEnumerator.
*/
- (NSArray *)dejal_arrayWithObjectsMatching:(id)match usingSelector:(SEL)selector
{
__block NSMutableArray *array = [NSMutableArray array];
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
if ([[obj performSelector:selector] dejal_isEquivalentTo:match])
{
[array addObject:obj];
}
}];
return array;
}
/**
Returns a new array containing the values returned by the specified selector for each object in the receiver. The selector would normally be an accessor, and must take no parameters and return an object value.
@author DJS 2004-02.
@version DJS 2014-09: changed to use block enumeration instead of NSEnumerator.
*/
- (NSArray *)dejal_arrayUsingSelector:(SEL)selector
{
__block NSMutableArray *array = [NSMutableArray array];
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
[array addObject:[obj performSelector:selector]];
}];
return array;
}
/**
Returns a new array containing all objects of the receiver other than the specified one.
@author DJS 2010-07.
*/
- (NSArray *)dejal_arrayByRemovingObject:(id)object;
{
NSMutableArray *array = [self mutableCopy];
[array removeObject:object];
return array;
}
/**
Returns a new array containing all objects of the receiver other than the specified one.
@author DJS 2010-07.
*/
- (NSArray *)dejal_arrayByRemovingObjectAtIndex:(NSUInteger)idx;
{
NSMutableArray *array = [self mutableCopy];
[array removeObjectAtIndex:idx];
return array;
}
/**
Returns a new array containing only the objects from the receiver that are not also in the other array.
@author DJS 2004-04.
*/
- (NSArray *)dejal_arrayByRemovingObjectsInArray:(NSArray *)otherArray
{
NSMutableArray *array = [self mutableCopy];
[array removeObjectsInArray:otherArray];
return array;
}
/**
Returns a reversed edition of the reciever.
@author DJS 2004-03.
@version DJS 2014-10: changed to use a modern block approach.
*/
- (NSArray *)dejal_reverseArray;
{
NSMutableArray *array = [NSMutableArray arrayWithCapacity:self.count];
[self enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
[array addObject:obj];
}];
return array;
}
/**
Returns a copy of the receiver sorted as in the Finder.
@author DJS 2008-01.
*/
- (NSArray *)dejal_sortedArrayUsingFinderOrder;
{
return [self sortedArrayUsingSelector:@selector(localizedStandardCompare:)];
}
/**
Given a property key (i.e. an accessor name), returns the receiver sorted by that value. (If the values of the key are not likely to be unique, it'd be better to do this manually, to sort on two keys, and thus avoid random ordering of same primary values.)
@author DJS 2010-10.
*/
- (NSArray *)dejal_sortedArrayUsingKey:(NSString *)key ascending:(BOOL)ascending;
{
return [self sortedArrayUsingDescriptors:@[[[NSSortDescriptor alloc] initWithKey:key ascending:ascending]]];
}
/**
Returns YES if the object is already in the array.
*/
- (BOOL)dejal_containsObjectIdenticalTo:(id)obj
{
return [self indexOfObjectIdenticalTo:obj] != NSNotFound;
}
/**
Returns YES if the receiver contains an object that is equivalent to the specified one. See -isEquivalentTo:.
@author DJS 2005-05.
*/
- (BOOL)dejal_containsObjectEquivalentTo:(id)obj
{
return [self dejal_indexOfObjectEquivalentTo:obj] != NSNotFound;
}
/**
Returns the index of the first object in the receiver that is equivalent to the specified one. If none is found, returns NSNotFound. See -isEquivalentTo:.
@author DJS 2005-05.
*/
- (NSUInteger)dejal_indexOfObjectEquivalentTo:(id)obj
{
NSUInteger i = 0;
id object = nil;
BOOL found = NO;
while (!found && i < [self count])
{
if ((object = self[i]))
found = [object dejal_isEquivalentTo:obj];
if (!found)
i++;
}
if (found)
return i;
else
return NSNotFound;
}
/**
Returns the first object in the array that passes a test in a given block.
@param predicate The block to apply to elements in the array.
@returns The first object in the receiver that passes the test specified by the predicate. If no objects pass the test, returns nil..
@author DJS 2014-10.
*/
- (id)dejal_objectPassingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate;
{
__block id foundObject = nil;
[self indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop)
{
if (predicate(obj, idx, stop))
{
foundObject = obj;
return YES;
}
return NO;
}];
return foundObject;
}
/**
Returns the second-to-last object in the array, or nil if the array is empty or only contains one object.
@author DJS 2003-06.
*/
- (id)dejal_penultimateObject
{
NSUInteger numberOfItems = [self count];
if (numberOfItems >= 2)
return self[numberOfItems - 2];
else
return nil;
}
/**
Similar to -copy, but each of the objects in the array are copied too. Note that like -copy, the array is retained.
@author DJS 2004-06.
@version DJS 2006-01: changed to fix memory leak through excessive retaining.
*/
- (id)dejal_deepCopy
{
id array = [[NSMutableArray alloc] init];
id copy;
for (id object in self)
{
if ([object respondsToSelector:@selector(dejal_deepCopy)])
copy = [object dejal_deepCopy];
else
copy = [object copy];
[array addObject:copy];
}
return array;
}
/**
Similar to -deepCopy, above, but makes all of the contents of the dictionary mutable.
@author DJS 2009-01.
*/
- (id)dejal_deepMutableCopy;
{
id array = [[NSMutableArray alloc] init];
id mutableCopy;
for (id object in self)
{
if ([object respondsToSelector:@selector(dejal_deepMutableCopy)])
mutableCopy = [object dejal_deepMutableCopy];
else if ([object conformsToProtocol:@protocol(NSMutableCopying)])
mutableCopy = [object mutableCopy];
else
mutableCopy = [object copy];
[array addObject:mutableCopy];
}
return array;
}
@end
// ----------------------------------------------------------------------------------------
#pragma mark -
// ----------------------------------------------------------------------------------------
@implementation NSMutableArray (Dejal)
/**
Similar to -insertObject:atIndex:, but if the index is out of range, it inserts at the end (if atEnd is YES) or at the start (if atEnd is NO), rather than giving an exception. Returns the index the object was inserted at.
@author DJS 2004-01.
*/
- (NSUInteger)dejal_insertObject:(id)object atIndex:(NSUInteger)i orEnd:(BOOL)atEnd
{
NSUInteger count = [self count];
// Remember that the index can equal count for -insertObject:atIndex: -- that just means to insert afterwards, but check for it here in case atEnd is NO:
if (i > count)
{
if (atEnd)
i = count;
else
i = 0;
}
[self insertObject:object atIndex:i];
return i;
}
/**
Similar to -insertObject:atIndex:, but inserts multiple objects at the index position.
*/
- (void)dejal_insertObjectsFromArray:(NSArray *)array atIndex:(NSUInteger)i
{
id object;
for (object in array)
{
[self insertObject:object atIndex:i++];
}
}
/**
Inserts objects from the specified array at the index position, removing them from their old position if already present. If the index is invalid, the objects are added to the array (instead of causing an exception). The adjusted index is returned; it is adjusted if some old indexes were before the new index.
@author DJS 2003-11.
@version DJS 2007-04: changed to return the adjusted index.
*/
- (NSUInteger)dejal_insertOrMoveObjectsFromArray:(NSArray *)array atIndex:(NSUInteger)i;
{
id object;
for (object in array)
{
NSUInteger existing = [self indexOfObject:object];
if (existing != NSNotFound)
{
if (existing < i)
i--;
[self removeObjectAtIndex:existing];
}
}
if ([self dejal_isValidIndex:i])
[self dejal_insertObjectsFromArray:array atIndex:i];
else
{
i = [array count];
[self addObjectsFromArray:array];
}
return i;
}
/**
Adds objects from the specified array, removing them from their old position if already present.
@author DJS 2003-11.
*/
- (void)dejal_addOrMoveObjectsFromArray:(NSArray *)array
{
[self dejal_insertOrMoveObjectsFromArray:array atIndex:-1];
}
/**
Given an enumerator for an array of index numbers (e.g. as used in NSTableView's -selectedRowsEnumerator), this returns a new mutable array containing the corresponding objects from the receiver.
@author DJS 2004-01.
*/
- (NSMutableArray *)dejal_arrayWithIndexEnumerator:(NSEnumerator *)enumerator
{
NSMutableArray *array = [NSMutableArray array];
NSNumber *i;
while ((i = [enumerator nextObject]))
{
id object = self[[i integerValue]];
if (object)
[array addObject:object];
}
return array;
}
/**
Given an enumerator for an array of index numbers (e.g. as returned by -[NSTableView selectedRowsEnumerator]), this removes the corresponding objects from the receiver.
@author DJS 2004-01.
*/
- (void)dejal_removeObjectsFromIndexEnumerator:(NSEnumerator *)enumerator
{
[self removeObjectsInArray:[self dejal_arrayWithIndexEnumerator:enumerator]];
}
/**
Given a value to match and a key to use to find that value, this removes the corresponding objects from the receiver. Useful for removing all dictionaries in an array that have the match value.
@author DJS 2005-03.
*/
- (void)dejal_removeObjectsMatching:(id)match usingKey:(NSString *)key
{
[self removeObjectsInArray:[self dejal_arrayWithObjectsMatching:match usingKey:key]];
}
/**
Returns a mutable reversed edition of the reciever.
@author DJS 2004-03.
*/
- (NSMutableArray *)dejal_reverseArray
{
return [[super dejal_reverseArray] mutableCopy];
}
/**
Makes an immutable copy of the receiver, then sends the selector to each object in the array. This should be used instead of -makeObjectsPerformSelector: for mutable arrays, since they could raise an exception if the array is mutated during enumeration (e.g. as a side-effect of the selector method).
@author DJS 2011-04.
*/
- (void)dejal_makeObjectsSafelyPerformSelector:(SEL)selector;
{
NSArray *immutableArray = [self copy];
[immutableArray makeObjectsPerformSelector:selector];
}
/**
Convenience method to use a mutable array as a queue; adds the object to the end of the queue.
@author DJS 2014-04.
*/
- (void)dejal_enqueue:(id)obj;
{
[self addObject:obj];
}
/**
Convenience method to use a mutable array as a queue; removes the first object from the queue and returns it.
@author DJS 2014-04.
*/
- (id)dejal_dequeue;
{
id first = [self firstObject];
if (first)
[self removeObjectAtIndex:0];
return first;
}
/**
Convenience method to use a mutable array as a stack; adds the object to the top (end) of the stack.
@author DJS 2014-04.
*/
- (void)dejal_push:(id)obj;
{
[self addObject:obj];
}
/**
Convenience method to use a mutable array as a stack; removes the top (end) object from the stack and returns it.
@author DJS 2014-04.
*/
- (id)dejal_pop;
{
id last = [self lastObject];
if (last)
[self removeLastObject];
return last;
}
@end