【问题标题】:Objective C - NSMutableSet not working properly目标 C - NSMutableSet 无法正常工作
【发布时间】:2013-12-12 23:36:17
【问题描述】:

我有一个要添加标签的 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]);
    }
}

【问题讨论】:

  • 仅供参考 - 不要在 .h 文件中声明 letters。放到它所属的.m文件中。

标签: objective-c cocos2d-iphone nsmutableset


【解决方案1】:

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

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

…或在您的 initiateLetters 方法的开头:

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

相反,您发布的代码只是将addObject: 发送到nil,这没有任何作用。

【讨论】:

  • initiateLetters 方法中初始化letters 可能是一个更好的选择。
【解决方案2】:

数组可能为零。你是在类的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];    
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    • 2019-04-13
    • 2012-11-12
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多