cocos2d组相同的字符串

时间:2012-03-21 15:48:05

标签: objective-c cocos2d-iphone nsstring

我正在从一些字符串生成一个列表,最多4个

  NSUInteger total = MIN(4, myNSMutableArray.count);
    CGFloat xPos = 0.0f;
    CGFloat yPos = 450.0f;
    CGFloat yPadding = 10.0f;
    NSInteger count = 0;
    for (ItemClass *item in myNSMutableArray) {
      if (count == total) return;

         CCLabelTTF *itemLabel = [CCLabelTTF labelWithString:item.name 
                                                 dimensions: CGSizeMake(280, 50)
                                                  alignment:UITextAlignmentCenter
                                              lineBreakMode:UILineBreakModeWordWrap
                                                   fontName:@"MyFont.otf"
                                                   fontSize:28.0f];
        itemLabel.anchorPoint = ccp(0,0);
        itemLabel.position = ccp(xPos, yPos);
        itemLabel.tag = item.itemID;
        [self addChild:itemLabel];
        [myNSMutableArrayOfLabels addObject:itemLabel];
        yPos -= itemLabel.contentSize.height + yPadding;
        count++;
    }

让我留下我有字符串列表,如:字符串1,字符串2,字符串3,字符串3,字符串3,字符串3.我想将它们分组以获得类似的内容:

string 1
string 2
string 3 (4)

1 个答案:

答案 0 :(得分:2)

因为你的数据是NSMutableArray,所以很简单:

NSArray *sorted = [myArray sortedArrayUsingComparator:^(id obj1, id obj2) {
    assert([obj1 isKindOfClass:[ItemClass class]]);
    assert([obj2 isKindOfClass:[ItemClass class]]);

    ItemClass *item1 = obj1;
    ItemClass *item2 = obj2;

    return [item1.name compare:item2.name];
}];

for (ItemClass *item in sorted)
{
    // create your labels
}