forked from mikelaurence/CoreResource
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NSArray+Core.m
55 lines (40 loc) · 1.37 KB
/
NSArray+Core.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
//
// NSArray+Core.m
// CoreTest
//
// Created by Mike Laurence on 3/11/10.
// Copyright 2010 Mike Laurence. All rights reserved.
//
#import "NSArray+Core.h"
@implementation NSArray (Core)
#pragma mark -
#pragma mark Sorting
- (NSArray*) sortedArrayUsingKey:(id)key ascending:(BOOL)ascending {
return [self sortedArrayUsingFunction:ascending ? ascendingSort : descendingSort context:key];
}
NSInteger ascendingSort(id obj1, id obj2, void *key) {
return [[obj1 objectForKey:key] compare:[obj2 objectForKey:key]];
}
NSInteger descendingSort(id obj1, id obj2, void *key) {
return [[obj2 objectForKey:key] compare:[obj1 objectForKey:key]];
}
#pragma mark -
#pragma mark Mapping
- (NSArray*) arrayMappedBySelector:(SEL)selector {
return [self arrayMappedBySelector:selector withObject:nil];
}
- (NSArray*) arrayMappedBySelector:(SEL)selector withObject:(id)object {
NSMutableArray *array = [NSMutableArray arrayWithCapacity:[self count]];
for (id obj in self) {
if ([obj respondsToSelector:selector])
[array addObject:[obj performSelector:selector withObject:object]];
}
return array;
}
- (NSDictionary*) dictionaryMappedByKey:(id)key {
NSMutableDictionary* dict = [NSMutableDictionary dictionaryWithCapacity:[self count]];
for (id obj in self)
[dict setObject:obj forKey:[obj valueForKey:key]];
return dict;
}
@end