如果你习惯了绑定,那么我建议看看NSValueTransformer;特别是创建一个将优先级值转换为感叹号字符串的子类。然后,您只需在绑定中提供名称(与+setValueTransformer:forName:
中使用的名称相同)作为“值转换器”属性。
例如,代码看起来像这样:
@interface PriorityTransformer : NSValueTransformer
@end
@implementation PriorityTransformer
+ (Class) transformedValueClass { return ([NSString class]); }
+ (BOOL) allowsReverseTransformation { return (NO); }
- (id) transformedValue: (id) value
{
// this makes the string creation a bit simpler
static unichar chars[MAX_PRIORITY_VALUE] = { 0 };
if (chars[0] == 0)
{
// ideally you'd use a spinlock or such to ensure it's setup before
// another thread uses it
int i;
for (i = 0; i < MAX_PRIORITY_VALUE; i++)
chars[i] = (unichar) '!';
}
return ([NSString stringWithCharacters: chars
length: [value unsignedIntegerValue]]);
}
@end
你会然后把该代码放到同一个文件的核心类(如应用程序委托),并通过类的+initialize
方法注册它以确保它在任何笔尖上都能及时找到它:
+ (void) initialize
{
// +initialize is called for each class in a hierarchy, so always
// make sure you're being called for your *own* class, not some sub- or
// super-class which doesn't have its own implementation of this method
if (self != [MyClass class])
return;
PriorityTransformer * obj = [[PriorityTransformer alloc] init];
[NSValueTransformer setValueTransformer: obj forName: @"PriorityTransformer"];
[obj release]; // obj is retained by the transformer lookup table
}