views:

53

answers:

3

I'm not sure if I worded the subject correctly. I am looping through an array, within each loop I am trying to instantiate a class, but I want to dynamically create the name. Like so:

int i = 0;

for(NSString* thisdatarow in filedata) { 
    i++;
    NSString* thisad = [NSString stringWithFormat:@"ad%d", i];
    NSLog(@"%@", thisad);
    AdData* thisad = [AdData new];  
}

In the example above I want AdData* thisad... to be named dynamically - "ad1", "ad2", "ad3"...and so on. I get a conflicting type error.

This code also generated an error:

int i = 0;
for(NSString* thisdatarow in filedata) { 
    i++;
    AdData* [NSString stringWithFormat:@"ad%d", i] = [AdData new];
}

Is there a way to do this?

A: 

Cant be done Without using a C array, which would look like this:

AdData **ad = malloc(sizeof(AdData) * numberOfAds);
ad[1] = [AdData new];
// etc.
if (ad)
    free(ad);

But I don't know how that would work because of how Objective-C classes are stored....

Richard J. Ross III
+1  A: 

You can't do that in Objective-C.

Use a NSString to AdData map--it'll do basically the same thing!

**edit: To clarify, use an:

NSMutableDictionary *dict;

with keys that are NSString* objects containing the ad names, and values that are the AdData* objects.

i.e.

[dict setValue:ad1 forKey:@"ad1"];

to set the values, and

[dict valueForKey:@"ad1"];

to get the values. (ignore the obvious memory leaks there with the strings...)

Thanks everyone, this helps out a lot.
PruitIgoe
+2  A: 

This isn't possible. While Objective-C is very dynamic, it's not that dynamic.

The suggested way to do this would be to create your instances and put them into an array, not assigning them to explicitly named variables.

You can then refer to them individually using their index in the array.

Something like this:

NSMutableArray *ads = [NSMutableArray array];

for(NSString* thisdatarow in filedata) { 
    AdData* thisad = [[[AdData alloc] init] autorelease];  
    [ads addObject:thisad];
}

// get third ad:
AdData *ad = [ads objectAtIndex:2];

Alternatively you could create an NSDictionary, if you really want to refer to them by a name, like this:

NSMutableDictionary *ads = [NSMutableDictionary dictionary];
int i = 0;

for(NSString* thisdatarow in filedata) { 
    i++;
    AdData* thisad = [[[AdData alloc] init] autorelease];
    NSString *keyName = [NSString stringWithFormat:@"ad%d", i];
    [ads setObject:thisad forKey:keyName];
}

// get third ad
AdData *ad = [ads objectForKey:@"ad2"];
Jasarien
This is correct, but the `i` counter is useless if you're just appending to an array.
Chuck
You're right, I just copied the code example from the original question and didn't remove it.
Jasarien
I get this working up to this line: AdData *ad = [ads objectForKey:@"ad2"]; it crashes my app.
PruitIgoe
Well, let us know why it crashed and what was printed to the console and we might be able to help you. "It crashes" doesn't help.
Jasarien