编辑所选行中的单元格

时间:2009-05-18 01:35:16

标签: objective-c cocoa

显然,我一直在使用绑定太长时间,因为我无法弄清楚如何做到这一点。我有一个包含多个列的表。选择行后,您可以编辑其优先级,从而修改核心数据属性。我也把它设置为IBAction。基本上,我想从我的代码中访问Core Data属性的值。然后,我想将选择的任何行的第一列(并且其优先级已更改)设置为与优先级相对应的多个感叹号。

抱歉,这令人困惑;这是一个例子:

选择第7行。我将其优先级更改为2.现在,Core Data属性myPriority设置为2.现在触发代码块。它从Core Data获取所选行(第7行)的优先级,并希望将所选行(第7行)的第1列设置为2个感叹号(优先级2)。

谢谢!

1 个答案:

答案 0 :(得分:1)

如果您习惯于绑定,那么我建议您查看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方法进行注册,以确保它及时注册以供任何nib查找:< / p>

+ (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
}