2014-02-24 5 views
0

API 호출 결과에 따라 다른보기를 표시해야하는 iOS 응용 프로그램을 만듭니다. momment에서 나는 이것이이 느린 작동 코드를 많이 좋아하지만 난 그렇게IF 문을 사용하여보기 표시

CGRect rect = CGRectMake(180.0f, 24.0f, self.view.frame.size.width, self.view.frame.size.width); 
JHView *myView = [[JHFewCloudsView alloc] initWithFrame:rect]; 
[self.view myView]; 

같은 정확한 뷰를로드 IF 문을 형성하기 위해이 결과를 사용하여 다음, 데이터베이스 쿼리 결과를 저장하고 있어요 간단한 작업. 여러보기가 더 좋은 방법이 있습니까? 한 번에 많은 - (void)drawRect:(CGRect)rect을 사용할 수 있으며 필요한 관련 전화 번호로 전화 할 수 있습니까?

if ([icon isEqual: @"01d"]) 
    { 
     CGRect rect = CGRectMake(180.0f, 24.0f, self.view.frame.size.width, self.view.frame.size.width); 
     JHSunView *sunView = [[JHSunView alloc] initWithFrame:rect]; 
     [self.view addSubview:sunView]; 

    } else if ([icon isEqualToString:@"02d"]) 
    { 
     CGRect rect = CGRectMake(180.0f, 24.0f, self.view.frame.size.width, self.view.frame.size.width); 
     JHFewCloudsView *fewCloudsView = [[JHFewCloudsView alloc] initWithFrame:rect]; 
     [self.view addSubview:fewCloudsView]; 
    } 

내가 지금하고있는 방식은 이제 15 가지보기와 매우 복잡한 코드로 끝날 것임을 의미합니다.

+0

"'[self.view myView];'"나에게 맞지 않습니다. "'self.view = myView'"아마도 당신이 의미 한 것입니까? –

+0

'if' 코드를 보여줍니다. 조회 테이블을 사용할 수도 있습니다. 하지만 실제 문제는 현재 100 % 명확하지 않습니다 ... – Wain

+0

업데이트보기 @Wain 및 nope [self.view myView]가 정확함 – joshuahornby10

답변

0

코드가 질문과 같이 반복되는 경우 (유일한 차이는 클래스 이름 임) 키가 if 문에있는 문자열 인 사전을 만들 수 있으며 값은 클래스의 이름입니다 문자열로). 그런 다음 코드가된다 :

목표 - C에서
Class viewClass = NSClassFromString([self.viewConfig objectForKey:icon]); 
CGRect rect = CGRectMake(180.0f, 24.0f, self.view.frame.size.width, self.view.frame.size.width); 
UIView *newView = [[[viewClass alloc] initWithFrame:rect]; 
[self.view addSubview: newView]; 
0

, 각 클래스는 단지 다른 객체처럼 처리 할 수 ​​있습니다 (유형 Class의) 객체에 의해 표현된다. 특히 Class을 사전의 값으로 사용하여 변수에 저장하고 메시지를 보낼 수 있습니다. 따라서 :

static NSDictionary *viewClassForIconName(NSString *iconName) { 
    static dispatch_once_t once; 
    static NSDictionary *dictionary; 
    dispatch_once(&once, ^{ 
     dictionary = @{ 
      @"01d": [JHSunView class], 
      @"02d": [JHFewCloudsView class], 
      // etc. 
     }; 
    }); 
    return dictionary; 
} 

- (void)setViewForIconName:(NSString *)iconName { 
    Class viewClass = viewClassForIconName(iconName); 
    if (viewClass == nil) { 
     // unknown icon name 
     // handle error here 
    } 
    CGRect rect = CGRectMake(180.0f, 24.0f, self.view.frame.size.width, self.view.frame.size.width); 
    UIView *view = [[viewClass alloc] initWithFrame:rect]; 
    [self.view addSubview:view]; 
}