0

我有一个试图添加标签的 NSMutableSet。添加每个标签后,我检查集合的计数并返回为 0。任何帮助将不胜感激

在我的 .h 文件中:

@interface MainMenu : CCLayerColor {
    NSMutableSet* letters;
}

在我的 .m 文件中:

-(void)initiateLetters{
    //Grab the window size
    CGSize size = [[CCDirector sharedDirector] winSize];

    int i;
    for(i=0;i<100;i++){
        CCLabelTTF *label;
        int r = rand() % 35 + 60;
        char c = (char) r;
        label = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"%c",c] fontName:@"Courier" fontSize:30];
        [label setColor:ccc3(0,0,0)];
        [label setOpacity:255/2];

        //Generate a random number for the x variable, y will be 0
        int x = (arc4random() % (int)size.width);
        int y = size.height+(arc4random() % 50)+25;

        [label setPosition:ccp(x,y)];
        [self addChild:label];
        [letters addObject:label];

        //Here's what's printing 0:
        printf("%lu",[letters count]);
    }
}
4

2 回答 2

2

您必须先实例化集合,然后才能向其中添加内容。您可以在覆盖的实现中做到这一点init

- (id)init
{
    self = [super init];
    if (self) {
        letters = [[NSMutableSet alloc] init];
    }
    return self;
}

…或在您的initiateLetters方法开始时:

- (void)initiateLetters
{
    letters = [[NSMutableSet alloc] init];
    ...

相反,您发布的代码只是发送addObject:nil,它什么都不做。

于 2013-12-12T23:43:45.910 回答
0

数组可能为零。您是否在类 init 方法中创建它?

就像是

-(id) init { 

    if (self = [super init]){
        // ...
        letters = [[NSMutableSet set] retain];   // not using ARC
        // ...
    }
    return self;
}

而且当然

-(void) dealloc {

    // ...
    [letters release];              // not using ARC
    [super dealloc];    
}
于 2013-12-12T23:46:04.087 回答