2010-07-20 59 views
0

我有一堆存儲在NSArray中的NSDictionaries。字典存儲按鈕的座標,它們的名稱以及按下時加載的相關對象(UIView)。鍵值綁定iPhone

當按鈕被按下時,我可以檢索它是字符串格式的按鈕,例如「設置」,然後我想運行對象 - (void)設置{}。

現在我知道我會如何處理if else語句,但是我想避免它們,因爲它們很混亂,並認爲Key Value Bindings會是這樣,但我不相信它們存在於iPhone上。

它們在iPhone上可用嗎?我讀過的所有東西都說在iOS4中都沒有。如果他們是我將如何實現這一點。如果沒有,除了if語句之外,還有更好的方法嗎?我可以存儲對UIView的引用來推入NSArray而不是字符串,如果是這樣會影響性能嗎?

乾杯。

回答

2

鍵值綁定確實存在於iOS中,但您必須手動完成。你可以創建一個派生自「Button」的類,你可以創建一個你可以分配的NSDictionary屬性,並且在分配時,你可以開始觀察字典實例中的變化,並且在委託中你可以讀取值並賦值給self。

確定這裏是我的button.h文件

@interface MyCustomButton : NSButton 

NSDictionary* store; 

@end 

-(NSDictionary*) store; 
-(void) setStore: (NSDictionary*) v; 

,這裏是我的button.m文件

@implementation MyCustomButton 


-(void) dealloc{ 
    [self setStore: nil]; 
    [super dealloc]; 
} 

-(void) loadValues:{ 
    // fill your loading values here 
    // this is not correct you may need 
    // to see help to get correct names of 
    // function 
    [self setText: [store stringForKey:@"buttonLabel"]]; 
} 

-(void) setStore: (NSDictionary*) v{ 
    if(store!=nil){ 
     [store removeObserver: self forKeyPath:@"buttonLabel"]; 
     [store removeObserver: self forKeyPath:@"buttonX"]; 
     [store removeObserver: self forKeyPath:@"buttonY"]; 
     [store release]; 
    } 
    if(v==nil) 
     return; 
    store = [v retain]; 
    [store addObserver: self forKeyPath:@"buttonLabel" options:0 context:nil]; 
    [store addObserver: self forKeyPath:@"buttonX" options:0 context:nil]; 
    [store addObserver: self forKeyPath:@"buttonY" options:0 context:nil]; 

    [self loadValues]; 
} 

-(NSDictionary*) store{ 
    return [store autorelease]; 
} 

-(void) observeValueForKeyPath: (NSString*) keyPath 
    ofObject:(id)object 
    change:(NSDictionary*)change 
    context:(void*)context{ 
    // here you can identify which keyPath 
    // changed and set values for yourself 
    [self loadValues]; 
} 
@end 

並可能在代碼或徘徊無論你有myButton的實例,你需要開始做如下...

MyButton* button = [[[MyButton alloc] init] autorelease]; 

// add button to view... 

[button setStore: myDictionary]; 
// from this point onwards button will automatically 
// change its properties whenever dictionary 
// is modified 
+0

我認爲你有些事情要做,但你的回答很混亂,你能澄清一點嗎? – Rudiger 2010-07-20 23:03:20

+0

我已經添加了示例代碼,我還沒有測試過,但您可能需要調整它以使其正常工作。 – 2010-07-21 08:21:37

+0

謝謝,只是稍微澄清一點,但代碼也很好地工作:) – Rudiger 2010-07-21 22:09:59

2

如果你想做類和方法的運行時參考,你需要看看在Objective-C Runtime Referenc e。這會讓你通過使用字符串創建類並向它們發送消息。

+0

鍵值編碼用於訪問對象中的屬性,我看不出它會在這種情況下幫助我 – Rudiger 2010-07-20 23:01:35

+0

對不起,我被你誤用術語鍵值綁定 – willcodejavaforfood 2010-07-21 07:39:19