Re: naming variables on the fly
Re: naming variables on the fly
- Subject: Re: naming variables on the fly
- From: "M. Uli Kusterer" <email@hidden>
- Date: Wed, 8 Jun 2005 11:24:11 +0200
At 9:43 Uhr +0100 08.06.2005, Peter Browne wrote:
I apologize if this is a silly question, but I was wondering if/how
it is possible to dynamically name variables as they are created.
For instance, normally you would choose the name for a variable like
int i;
or NSString *aString;
but is there any way to program a situationally dependent
replacement for "i" or "aString". The only situation i can think of
for this is if, for some reason, you needed to initialize a varying
number of objects belonging to a custom class. Orr as a time saving
measure, for instance if you wanted to initialize 20 different
NSArrays could you do something along the lines of a:
for (someNumber = 0; someNumber <= 20; someNUmber++)
{
NSArray *aDifferentNameEachTime = [[NSArray alloc] init];
}
Any thoughts?
Either use an array of NSArray, or an NSDictionary. That's what
dynamic memory allocation is for. Except for some hacks that GCC lets
you do, variables are there for fixed-size storage. They're just a
shortcut so you can easily allocate little bits of memory without
having to resort to malloc(), and to solve the chicken-and-egg
problem of where to keep your pointers (for details, see
<http://zathras.de/angelweb/howmemorymanagementworks.htm>).
So, in your case, if 20 was a fixed number, I'd just use:
#define COUNT 20
NSMutableArray * arrayArray[COUNT];
for( int x = 0; x < COUNT; x++ )
arrayArray[x] = [NSMutableArray array]; // Autoreleased!
(I'm assuming you'd want a mutable array to be able to actually fill
them, or alternatively use arrayWithObjects:). Note that I'm using
-array instead of alloc/init here, as I'm assuming you'll only be
using this as long as arrayArray stays in scope, and if your
autorelease pool is outside the current function, this'll work just
fine.
If you need to pass around the array, you'll want an NSArray instead:
NSMutableArray * arrayNSArray = [NSMutableArray array];
for( int x = 0; x < COUNT; x++ )
{
[arrayNSArray addObject: [NSMutableArray array]];
/* arrayNSArray will retain this */
}
You can now retain arrayNSArray to keep it around, pass it off etc.
Similarly, you could use an NSDictionary to keep the other NSArrays,
which is like the NSArray approach above, but uses strings for the
keys (indexes) instead of numbers.
I hope I didn't get too complicated...?
--
Cheers,
M. Uli Kusterer
------------------------------------------------------------
"The Witnesses of TeachText are everywhere..."
http://www.zathras.de
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden