Reputation: 1130
I came across a requirement to parse xml or json and have to list them in table.
I have no problem in achieving this but i would like to optimize the code to use less memory resources.
The question is that is it best to have multiple arrays or is it better to have a single array whose contents are dictionaries.
please have a look at following example in which 3 names are saved in 2 ways
Way 1
NSArray* names = [NSArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:
@"rama krishna",@"firstname",
@"chunduri",@"surname",
nil],
[NSDictionary dictionaryWithObjectsAndKeys:
@"rama krishna",@"firstname",
@"gutta",@"surname",
nil],
[NSDictionary dictionaryWithObjectsAndKeys:
@"selvakumar",@"firstname",
@"k",@"surname",
nil],
nil];
Way 2
NSArray *firstnames=[NSArray arrayWithObjects:@"Rama Krishna",@"Rama Krishna",@"selvakumar",nil];
NSArray *surnames=[NSArray arrayWithObjects:@"chunduri",@"gutta",@"k",nil];
So, which one of these 2 ways can be prefered for optimized memory consumption.
Upvotes: 1
Views: 5884
Reputation: 14113
The better choice would be adding dictionary in an array. i.e one array and multiple dictionaries. I used this in my lastest application :
// In a loop
NSMutableDictionary *dictError=[NSMutableDictionary dictionaryWithObjectsAndKeys:maxCount,kID,kUsers,kEntity,[Utils convertDateInString:[NSDate date]],kDate,kTrue,kStatus,kEnter,kDescription, nil];
[arrError addObject:dictError];
In this way you can add dictionary as array objects.And to get indvisual disctionary object:
NSMutableDictionary *nameDictionary = [arrError objectAtIndex:1];
NSString *strEntityName = [nameDictionary objectForKey:@"KeyName"];
Upvotes: 0
Reputation: 17564
You have just encountered an excellent place to use object-oriented programming.
You dictionaries which map for example, "firstname" to "rama krishna" and "surname" to "gutta", should really be grouped into a class with an NSString*
instance variable for surname and firstname.
E.g.:
@interface Person : NSObject {
NSString *firstname;
NSString *surname;
}
@end
Then you will just have an array of Person
objects. Much easier to use, and the "correct" way to do things, in most cases. Anyone who touches your code will thank you.
Upvotes: 10