如果你習慣了綁定,那麼我建議看看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
}