开发者

How to sort an NSMutableArray of playing cards

I have a NSMutableArrary,It having the image of playing cards like as:

  1. 01-13 cards are Spades,
  2. 14-26 are Hearts,
  3. 27-39 are Diamonds,and
  4. 开发者_开发问答40-52 are Clubs.

I sort it Color wise using

[CopyArraryForShorting sortUsingSelector:@selector(caseInsensitiveCompare:)];

this cord ,But I'm fail to sort it arrary Number Wise.So plz tell me how to sort it.

arrayPlayerCard=[NSArray arrayWithObjects:[UIImage imageNamed:@"01.png"],
                                          [UIImage imageNamed:@"02.png"],
                        [UIImage imageNamed:@"03.png"],
                                          [UIImage imageNamed:@"04.png"],
                                          [UIImage imageNamed:@"05.png"],
                  [UIImage imageNamed:@"06.png"],
                                          [UIImage imageNamed:@"07.png"],
                                          [UIImage imageNamed:@"08.png"],................................................,nil]; 


I would create a custom class. Something like:

card.h

typedef enum {
    CardSuitSpade,
    CardSuitHeart,
    CardSuitClub,
    CardSuitDiamonds
}

@interface Card : NSObject {
    CardSuit    _suit;
    NSUInteger  _value;
}

- (id)initWithSuit:(CardSuit)suit andValue:(NSUInteger)value;

The implementation of this class would do the following:

  1. implement the initWithSuit:andValue: initializer
  2. validate the card value is between 0..12 (ace to king) when value is set and fail if not
  3. implement a comparator to compare two cards and return the appropriate comparison value

Then you can have an NSArray full of cards and sort it easily. You can also create methods to shuffle the deck, etc. Have fun creating your card game.


Create a custom class, or put the data in a NSDictionary. You cannot sort images (on their name), but you can sort on strings.

arrayPlayerCard=[NSArray arrayWithObjects:[NSDictionary dictionaryWithObjectsAndKeys:@"01", @"name", [UIImage imageNamed:@"01.png"], @"image", nil], ...

then sort using an NSSortDescriptor.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜