Reputation: 11201
I been searching for this but failed to find a proper solution. Is it possible to create an array for each object present in an array?Lets say I have an array 'fruits'
NSMutableArray *fruits=[[NSMutableArray alloc]init];
[fruits addObject:@"apple"];
[fruits addObject:@"banana"];
[fruits addObject:@"mango"];
Now there are three objects in my array. IS it possible to create an array for each of the object present in the array 'fruit'.
Can I do something like
for(int i=0;i<fruits.count;i++){
NSMutableArray *fruits_%d=[[NSMutableArray alloc]init];
}
I know it is a blunder. Is there any way I can do that?
Thanks in advance.
Upvotes: 0
Views: 162
Reputation: 1360
I don't know what exactly you want but maybe you can do something like this:
NSMutableArray *fruits = [[NSMutableArray alloc] init];
[fruits addObject:@"apple"];
[fruits addObject:@"banana"];
[fruits addObject:@"mango"];
NSMutableArray *arrayOfFruits = [[NSMutableArray alloc] initWithCapacity:fruits.count];
for (int i = 0; i < fruits.count; i++) {
[arrayOfFruits addObject:@[fruits[i]]];
}
Upvotes: 1
Reputation: 25687
You could use a dictionary instead:
NSMutableDictionary *fruitDict=[[NSMutableDictionary alloc]init];
[fruitDict setObject:[[NSMutableArray alloc]init] forKey:@"apple"];
[fruitDict setObject:[[NSMutableArray alloc]init] forKey:@"banana"];
[fruitDict setObject:[[NSMutableArray alloc]init] forKey:@"mango"];
Or a little cleaner syntax:
NSMutableArray *fruits=[[NSMutableArray alloc]init];
[fruits addObject:@"apple"];
[fruits addObject:@"banana"];
[fruits addObject:@"mango"];
NSMutableDictionary *fruitDict = [[NSMutableDictionary alloc] init];
for (NSString *fruit in fruits)
{
[fruitDict setObject:[[NSMutableArray alloc]init] forKey:fruit];
}
Then when you want to retrieve the array:
NSMutableArray *myArray = fruitDict[@"banana"]
The above code will yield the array for the banana item.
Upvotes: 2