2011-05-04 2 views
0

iPhone 용 Card 게임을 구현 중입니다. 내 모델 클래스에서 각 카드에는 N 개의 속성이 있습니다.외부 클래스 메소드에서 2 인스턴스의 속성 비교 - iPhone Card Game에 필요합니다.

@interface Card : NSObject { 

    NSInteger attribute1; 
    NSInteger attribute2; 
     ....................; 

    NSInteger attributeN; 
} 

사용자가 인터페이스에서 선택한 속성에 대해 2 개의 카드를 비교하는 컨트롤러 클래스를 만들고 싶습니다. 문제는 컨트롤러 클래스에 의해 외부 카드의 속성을 참조하는 방법을 모른다는 것입니다.

예 : 사용자가 Attribute를 클릭하면 컨트롤러 클래스에서 이와 같은 메소드가 호출되기를 원합니다.

- (Player) winnerOfComparisonBetween:(Card *) card1 andCard:(Card *) card2 forAttribute:??? { 
    if (card1.selectedAttribute** < card2.selectedAttribute) 
     return card1.owner 

    .... 
    .... 
} 

이 방법을 구현하는, 그리고 questionmarks 대신에 무엇을 넣어하는 방법에 어떤 아이디어? 어떤 도움이라도 대단히 감사 할 것입니다.

답변

2

NSObject의 performSelector 및 NSSelectorFromString을 살펴보십시오. 방법 :이 코드는 모든 속성이 비교를 구현한다고 가정하지만

- (Player)winnerOfComparisonBetween:(Card *)card1 andCard:(Card *)card2 forAttribute:(NSString *)attributeName { 

    SEL selector = NSSelectorFromString(attributeName); 
    id a = [card1 performSelector:selector]; 
    id b = [card2 performSelector:selector]; 

    NSComparisonResult result = [a compare:b]; 

    if (NSOrderedAscending == result) 
     return card1.owner; 
    else if (NSOrderedDescending == result) 
     return card2.owner; 
    else 
     NSLog(@"They're the same"); 
} 

:

는 다음과 같이하십시오. (NSString은 이미 그렇게 할 수 있습니다.)

또한 모든 속성이 객체라고 가정 할 경우 즉, 부동 또는 int를 가질 수 없다면 NSNumber가 있어야합니다.

그리고 거기가 더 읽을 수 있도록 확인 오류 없습니다 - 당신이 여기서 attributeName은 속성에 대한 유효한 이름되었는지 확인해야는하거나 충돌 할 수 있습니다 - respondsToSelector를 살펴 : 카드 객체가 수행 할 수 있는지 확인하는 선택은 :

0

사용이 하나의 당신이 여전히 문제가있는 경우, ... 알려주세요 :)

- (Player) winnerOfComparisonBetween:(Card *) card1 andCard:(Card *) card2 forAttribute:(NSInteger)attribute { 


    switch (attribute) { 
     case attribute1: 
      if (card1.attribute1 < card2.attribute1) 
       return card1.owner 
       } 
      break; 


     case attribute2: 
      if (card1.attribute2 < card2.attribute2) 
       return card1.owner 
       } 
      break; 


     . 
     . 
     . 
     . 
     . 

     case attributeN: 
      if (card1.attributeN < card2.attributeN) 
        return card1.owner 
       } 
      break; 


     default: 
      break; 
}