-
Notifications
You must be signed in to change notification settings - Fork 41
/
NSArray+Stringing.m
119 lines (101 loc) · 2.55 KB
/
NSArray+Stringing.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
#import "NSArray+Stringing.h"
@implementation NSArray (Stringing)
- (NSString*)listValuesOnePerLineForKeyPath:(NSString*)keyPath
bullet:(NSString*)bullet {
NSInteger nItems = [self count] ;
if (!keyPath) {
keyPath = @"description" ;
}
if (!bullet) {
bullet = @"" ;
}
NSMutableString* string = [[NSMutableString alloc] init] ;
NSInteger i ;
for (i=0; i<nItems; i++) {
NSString* value = [[self objectAtIndex:i] valueForKeyPath:keyPath] ;
if (value) {
if ((i>0)) {
[string appendString:@"\n"] ;
}
[string appendFormat:
@"%@%@",
bullet,
value] ;
}
}
NSString* output = [string copy] ;
[string release] ;
return [output autorelease] ;
}
- (NSString*)listValuesOnePerLineForKeyPath:(NSString*)keyPath {
return [self listValuesOnePerLineForKeyPath:keyPath
bullet:nil] ;
}
- (NSString*)listValuesForKey:(NSString*)key
conjunction:(NSString*)conjunction
truncateTo:(NSInteger)truncateTo {
NSArray* array ;
BOOL ellipsize = NO ;
if ((truncateTo > 0) && (truncateTo < [self count])) {
array = [self subarrayWithRange:NSMakeRange(0, truncateTo)] ;
ellipsize = YES ;
}
else {
array = self ;
}
if (!key) {
key = @"description" ;
}
NSInteger nItems = [array count] ;
NSMutableString* string = [[NSMutableString alloc] init] ;
NSInteger i ;
for (i=0; i<nItems; i++) {
id object = [array objectAtIndex:i] ;
NSString* value = nil ;
if ([object respondsToSelector:NSSelectorFromString(key)]) {
value = [object valueForKey:key] ;
}
else {
value = [object description] ;
}
if (![value isKindOfClass:[NSString class]]) {
continue ;
}
if ([value length] == 0) {
continue ;
}
if ((i==(nItems-1)) && (nItems>1) && conjunction) {
[string appendString:@" "] ;
if (conjunction) {
[string appendString:conjunction] ;
}
[string appendString:@" "] ;
}
else if ((i>0)) {
[string appendString:@", "] ;
}
[string appendString:value] ;
}
if (ellipsize) {
[string appendFormat:@", %C", (unsigned short)0x2026] ;
}
NSString* output = [string copy] ;
[string release] ;
return [output autorelease] ;
}
- (NSString*)listNames {
return [self listValuesForKey:@"name"
conjunction:nil
truncateTo:0] ;
}
- (NSString*)listDescriptions {
return [self listValuesForKey:@"description"
conjunction:nil
truncateTo:0] ;
}
- (NSString*)listValuesForKey:(NSString*)key {
return [self listValuesForKey:key
conjunction:nil
truncateTo:0];
}
@end