Objective C - NSMutableSet无法正常工作

时间:2013-12-12 23:36:17

标签: objective-c cocos2d-iphone nsmutableset

我有一个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]);
    }
}

2 个答案:

答案 0 :(得分:2)

您必须先实例化该集,然后才能向其添加内容。您可以在init

的重写实现中执行此操作
- (id)init
{
    self = [super init];
    if (self) {
        letters = [[NSMutableSet alloc] init];
    }
    return self;
}

...或在initiateLetters方法的开头:

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

相反,您发布的代码只是将addObject:发送给nil,而该代码无效。

答案 1 :(得分: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];    
}