Reputation: 11
I'm learning Objective-C. I would like to create a lot of mutable arrays of NSStrings with names like a5 and c11 etc. The first would be an array of 5-letter words all beginning with a, the second an array of 11-letter words all beginning with c and so on. The idea is to speed up searches as the number of entries becomes very large. I can easily build up the name of an array as a string using a couple of nested loops and by examining the length of the word I want to enter and its first letter.
But if I do build a string "a5" how do I get from there to sending a message [a5 message]
Also, is there a way I can first declare the arrays in my ArrayManager class without painstakingly typing in all the individual array declarations (26*15 arrays)?
Thanks if anyone can help.
Steve Hill
Upvotes: 1
Views: 78
Reputation: 86661
You can't do it directly because the variable name "a5" does not have any meaning outside of your source code. Once it is compiled, it's just an address.
I would use a dictionary, like this:
NSMutableDictionary* index = [[NSMutableDictionary alloc] init];
for (char letter = 'a' ; letter <= 'z' ; ++letter)
{
for (int length = 1 ; length <= 15 ; ++length)
{
NSString* key = [NSString stringWithFormat: @"%c%02d", letter, length]; // lengths are padded in case sorting is needed
[index setObject: [NSMutableArray array] forKey: key];
}
}
That pre-creates all your arrays for all letter number combinations. To use a particular array:
[[index objectForKey: @"a08"] addObject: @"aardvark"];
Of course, you'd wrap all of this in a class in real life.
Upvotes: 0
Reputation: 69037
I don't know if there is a way to synthesize an NSArray
name in Objective-C (and I doubt it, actually), but I would suggest you an alternative approach.
You could use an NSMutableDictionary
to collect all of your arrays. The keys in the dictionary would be: a5
, c11
, etc.
You would add a new array to the dictionary like this:
NSMutableDictionary allArrays = [[NSMutableDictionary alloc] init];
NSString* arrayName = @"...";
NSMutableArray* words = ...
[dict setObject:words forKey:arrayName];
....
....
[self doSomething:[dict objectForKey:@"a5"]]; //-- here you would access the array
Say that instead of your arrays having symbolic names at the Objective-C level, they have names that are meaningful to your program and that allow you to use them.
Upvotes: 3