在选定行中编辑单元格
问题描述:
显然,我一直在使用绑定太久,因为我无法弄清楚如何做到这一点。我有一个有几列的表。选择一行时,您可以编辑其优先级,从而修改核心数据属性。我也将其设置为IBAction。基本上,我想从我的代码中访问Core Data属性的值。然后,我想将所选行的第一列(并将其优先级更改)设置为与优先级相对应的许多感叹号。在选定行中编辑单元格
对不起,这是措辞混乱;这里是一个例子:
第7行被选中。我将其优先级更改为2.现在,核心数据属性myPriority设置为2.现在触发代码块。它获得所选行(第7行)形式的Core Data的优先级,并希望将所选行(第7行)的第1列设置为2个惊叹号(优先级2)。
谢谢!
答
如果你习惯了绑定,那么我建议看看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
}