Using a For Loop


#1

I was trying to use a for loop to create my three instances of StockHolding but I couldn’t figure out how (or if) I can use my counter in the naming convention.

I originally expected this to work;

// Create three stock items
    for (int i = 1; i < 4; i++) {
            StockHolding *"Stock" & i =[[StockHolding alloc] init];
        }

But that didn’t work so I tried multiple variations of

StockHolding *Stock & i =[[StockHolding alloc] init];
StockHolding *Stock.i =[[StockHolding alloc] init];
StockHolding *Stock(i) =[[StockHolding alloc] init];

And so on, but I could never figure out the syntax. There is a way to do this right?

–Dave


#2

You don’t have to create named objects, you can create an object and add it to an NSArray - or if you really like it to have a name, you can use an NSDictionary.

[code] NSMutableArray *stockHoldings = [NSMutableArray array];

    for (int i = 1; i<6; i++) {
        StockHolding *sh = [[StockHolding alloc] init];
        [sh setPurchaseSharePrice:i*20];
        [sh setCurrentSharePrice:i*15];
        [sh setNumberOfShares:i];
        [stockHoldings addObject:sh];
    }

[/code]

For as far as I know there’s no way to create variables in (Objective-)C during runtime. There is a way to add instance variables to a class at runtime (class_addIvar), but I haven’t used that myself. Here you can find more info on this: stackoverflow.com/questions/2166 … bjective-c


#3

Thanks for the response. I’ve had a chance to sit down with someone and give a detailed explanation to me why I can’t do what I thought I could do. It was a good explanation on how compliers work.