开发者

Compare properties of 2 instances from an external class method - Needed for iPhone Card Game

I am implementing a Card game for iphone. In my model class each Card has N attributes.

@interface Card : NSObject {

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

    NSInteger attributeN;
}

I want to make a Controller Class wich compares 2 cards, for the attribute开发者_开发百科 the user chooses from the interface. The problem is that i do not know how to refer to the attributes of the external card, by the Controller class.

eg. When the user clicks on an Attribute i want a method like this to be called on the controller class.

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

     ....
     ....
}

Any ideas on how to implement this method, and what to put in place of the questionmarks? Any help would be really appreciated.


Take a look at NSObject's performSelector and NSSelectorFromString.

Try something like this :

- (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");
}

Though this code assumes that all the attributes implement the compare: method. (NSStrings already do so you're probably OK)

If also assumes that all the attributes are objects i.e. you can't have floats or ints, you'd have to have NSNumbers.

And there's no error checking to make it more readable - you would need to make sure that attributeName was a valid name for an attribute or it might crash - take a look at respondsToSelector: to check if your card objects can perform the selector :)


Use this one if you have still problem with that, let me know... :)

- (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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜