2009-05-18 180 views
0

顯然,我一直在使用綁定太久,因爲我無法弄清楚如何做到這一點。我有一個有幾列的表。選擇一行時,您可以編輯其優先級,從而修改核心數據屬性。我也將其設置爲IBAction。基本上,我想從我的代碼中訪問Core Data屬性的值。然後,我想將所選行的第一列(並將其優先級更改)設置爲與優先級相對應的許多感嘆號。在選定行中編輯單元格

對不起,這是措辭混亂;這裏是一個例子:

第7行被選中。我將其優先級更改爲2.現在,核心數據屬性myPriority設置爲2.現在觸發代碼塊。它獲得所選行(第7行)形式的Core Data的優先級,並希望將所選行(第7行)的第1列設置爲2個驚歎號(優先級2)。

謝謝!

回答

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方法註冊它以確保它在任何筆尖上都能及時找到它:

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