1st challenge - build up object names?


#1

I was trying to make my first challenge code more generic and ran into a problem.
My code:

[code]#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{

@autoreleasepool {
    //create an empty array
    NSMutableArray *groceries = [NSMutableArray array];

	//create some items to put into the array
	NSString *item1 = @"Milk";
	NSString *item2 = @"Chocolate";
	NSString *item3 = @"Bread";
	NSString *item4 = @"Cheese";

	// add itemi to the array
	for (int i = 1; i < 5; i++) {
		NSString *localItem = [NSString stringWithFormat:@"item%d", i];
		//NSLog(@"%@",localItem);
		[groceries addObject:localItem];
	}
	
            //print out the array
	for (NSString *item in groceries) {
		NSLog(@"%@", item);
	}
    
}
return 0;

}
[/code]

I was trying to automate adding the items to the array with a for loop. If more items were created, I could just up to loop limit. So I created an NSString to hold the itemn name, but when I try to use localItem to reference item1 or item2, I just get “item1”, or “item2”, not the value that they are pointing to.

So as it is written, my array ends up [item1, item2, item3, item4], not [Milk, Chocolate, Bread, Cheese]. How can I get it to translate the NSString item1 stored in localItem as a variable name to be translated as well?

Thanks,


#2

I see what you are doing here, and it is admirable, but Objective-C doesn’t give you a way to get the value of a variable from its name as a string.

If item1, item2, etc. were instance variables of an object, you could use key-value coding:

NSString *x = [myObj valueForKey:localItem];
But, there is no similar way to access local variables.