2010-07-20 7 views
0

나는 NSArray에 저장된 NSDictionaries를 많이 가지고 있습니다. 사전은 버튼, 해당 이름 및 눌렀을 때로드 할 관련 객체에 대한 좌표를 저장합니다 (UIView).키 값 바인딩 iPhone

단추를 누르면 문자열 형식의 단추 (예 : "settings")를 검색 할 수 있으며 개체 - (void) 설정 {}을 실행하려고합니다.

이제는 else 문과 함께하는 방법을 알고 있지만 지저분하고 Key Value Bindings가 길일 것이라고 생각했기 때문에 피하고 싶습니다. 그러나 나는 iPhone에 존재한다고 생각하지 않습니다.

iPhone에서 사용할 수 있습니까? 내가 읽은 모든 것은 iOS4에서도 마찬가지입니다. 그들이 내가 이것을 어떻게 구현할 것인가라면. 그렇지 않다면 else 문 이외에 이것을하기위한 더 좋은 방법이 있습니까? 문자열 대신 NSArray를 푸시하기 위해 UIView에 대한 참조를 저장할 수 있습니까? 그렇다면 성능에 영향을 미칩니 까?

건배.

답변

2

키 값 바인딩은 iOS에 존재하지만 수동으로해야합니다. "Button"에서 파생 된 클래스를 만들 수 있으며 할당 할 수있는 NSDictionary의 속성을 만들 수 있습니다. 할당 할 때 사전 인스턴스에서 변경 사항을 관찰 할 수 있으며 델리게이트에서 값을 읽고 자체에 할당 할 수 있습니다. 여기에 좋아

내 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에의 인스턴스가 whereever 당신이 필요로하는 또는 코드의 시작 부분에서 내 button.h 파일

@interface MyCustomButton : NSButton 

NSDictionary* store; 

@end 

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

이며, 여기에 다음을 수행하십시오 ...

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

+0

샘플 코드를 추가했지만 아직 테스트하지는 않았지만 제대로 작동하려면 수정해야 할 수도 있습니다. –

+0

고마워요, 조금 더 명확 해 지긴했지만 코드도 멋지게 작동합니다 :) – Rudiger

2

클래스 및 메소드의 런타임 참조를 원할 경우 Objective-C에서 Runtime Referenc e. 이렇게하면 문자열을 사용하여 클래스를 만들고 메시지를 보낼 수 있습니다.

+0

키 값 코딩은 객체의 속성에 액세스하는 데 사용됩니다.이 인스턴스에서 나를 도울 방법은 없습니다 – Rudiger

+0

오용으로 인해 혼란 스러웠습니다. 용어 키 값 바인딩 – willcodejavaforfood