Creating NSFormatters(Chapter 26 of Cocoa Programming for Mac OS X)
1 #import "ColorFormatter.h"2
3 @interface ColorFormatter()
4
5 - (NSString *)firstColorKeyForPartialString:(NSString *)string;
6
7 @end
8
9 @implementation ColorFormatter
10
11 - (id)init
12 {
13 ;
14 colorList = [ retain];
15 return self;
16 }
17
18 - (void)dealloc
19 {
20 ;
21 ;
22 }
23
24 - (NSString *)firstColorKeyForPartialString:(NSString *)string
25 {
26 if( == 0)
27 {
28 return nil;
29 }
30
31 for(NSString *key in )
32 {
33 NSRange whereFound = ;
34 if ((whereFound.location == 0) && (whereFound.length > 0))
35 {
36 return key;
37 }
38 }
39
40 return nil;
41 }
42
43 - (NSString *)stringForObjectValue:(id)obj
44 {
45 if(!])
46 {
47 return nil;
48 }
49
50 NSColor *color;
51 color = ;
52
53 CGFloat red, green, blue;
54 ;
55
56 float minDistance = 3.0;
57 NSString *closestKey = nil;
58 for(NSString *key in )
59 {
60 NSColor *c = ;
61 CGFloat r, g, b;
62 ;
63
64 float dist;
65 dist = pow(red-r, 2) + pow(green-g, 2) + pow(blue-b, 2);
66 if(dist < minDistance)
67 {
68 minDistance = dist;
69 closestKey = key;
70 }
71 }
72
73 return closestKey;
74 }
75
76 - (BOOL)getObjectValue:(id *)obj forString:(NSString *)string errorDescription:(NSString **)error
77 {
78 NSString *matchingKey = ;
79 if(matchingKey)
80 {
81 *obj = ;
82 return YES;
83 }
84 else
85 {
86 if(error != NULL)
87 {
88 *error = ;
89 }
90 return NO;
91 }
92
93 }
94
95 /*
96 - (BOOL)isPartialStringValid:(NSString *)partialString newEditingString:(NSString **)newString errorDescription:(NSString **)error
97 {
98 if( == 0)
99 {
100 return YES;
101 }
102
103 NSString *match = ;
104 if(match)
105 {
106 return YES;
107 }
108 else
109 {
110 if (error)
111 {
112 *error = @"No such color";
113 }
114 return NO;
115 }
116 }
117 */
118
119 - (BOOL)isPartialStringValid:(NSString **)partial proposedSelectedRange:(NSRange *)selPtr originalString:(NSString *)origString originalSelectedRange:(NSRange)origSel errorDescription:(NSString **)error
120 {
121 if([*partial length] == 0)
122 {
123 return YES;
124 }
125
126 NSString *match = ;
127 if(!match)
128 {
129 return NO;
130 }
131
132 if (origSel.location == selPtr->location)
133 {
134 return YES;
135 }
136
137 if( != [*partial length])
138 {
139 selPtr->location = [*partial length];
140 selPtr->length = - selPtr->location;
141 *partial = match;
142 return NO;
143 }
144
145 return YES;
146 }
147
148 - (NSAttributedString *)attributedStringForObjectValue:(id)obj withDefaultAttributes:(NSDictionary *)attrs
149 {
150 NSMutableDictionary *md = ;
151 NSString *match = ;
152 if(match)
153 {
154 ;
155 }
156 else
157 {
158 match = @"";
159 }
160 NSAttributedString *atString;
161 atString = [ initWithString:match attributes:md];
162 ;
163 ;
164 return atString;
165 }
166
167 @end
页:
[1]