Search code examples
objective-cvariablessprite-kitdeclarationsknode

How can I declare and initialize a n° of variables without knowing how many are?


Let me explain what I mean:

I need to declare and init a number x of SKNode variables (between 1 and 15) based on which value is passed through the method:

- (instancetype)initWithNumberOfNodes:(int)number;

Every SKNode will be added into a NSMutableArray so I won't have problem with references (I will get every single items with [myArray objectAtIndex:]). I don't think that create 15 SKNode variables could be the best solution due to the large wasting of memory and an odd programming style.

Any clues?


Solution

  • If you know you're going to need 15, or whatever number is, you can store that in a property:

    @property (nonatomic, assign) NSUInteger number;
    
    - (instancetype)initWithNumberOfNodes:(int)number {
        // ... normal stuff ...
    
            self.number = number;
            self.nodes = [NSMutableArray arrayWithCapacity:number];
    
            // Populate with placeholders to avoid out of bounds access later.
            for (int i = 0; i < number; ++i) { 
                self.nodes[i] = [NSNull null];  
            }
    
        // ... normal stuff ...
    }
    

    Then, write yourself a little helper to lazily create them.

    - (SKNode*)nodeAtIndex:(NSUInteger)index {
        NSAssert(index < self.number, @"bad index");
    
        SKNode* node = [self.nodes objectAtIndex:index];
        if ([node isKindOfClass:[NSNull class]]) {
            node = [[SKNode alloc] init];  // Or whatever.
            [self.nodes replaceObjectAtIndex:index withObject:node];
        }
        return node;
    }
    

    And use your helper whenever you need a node:

    SKNode* someNode = [self nodeAtIndex:someIndex];