I have created an array, two dictionaries and a tableview. The tableview should display the contents of array and that array contains the data of dictionaries. When i try to display it using “[mArray addObject:(mDictionary)];” its throwing an exception but if i use “[mArray addObject:[mDictionary objectForKey:@”firstname”]];” its working fine.
Can you help me to understand why is it happening and isn’t it possible to display the dictionary value without using “objectForKey”?
Here is my “ViewController.m”.
#import "ViewController.h"
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
mArray = [[NSMutableArray alloc]init];
mDictionary = [[NSMutableDictionary alloc]init];
[mDictionary setValue:@"shanu" forKey:@"firstname"];
[mDictionary setValue:@"kumar" forKey:@"lastname"];
mDictionary2 = [[NSMutableDictionary alloc]init];
[mDictionary2 setValue:@"hgjghjgf" forKey:@"firstname1"];
[mDictionary2 setValue:@"ghjgjgfj" forKey:@"lastname1"];
[mArray addObject:mDictionary];
[mArray addObject:mDictionary2];
CGRect frame = self.view.frame;
UITableView *tableView = [[UITableView alloc]initWithFrame:frame style:UITableViewStylePlain];
tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
tableView.backgroundColor = [UIColor cyanColor];
tableView.separatorColor = [UIColor blackColor];
tableView.delegate = self;
tableView.dataSource = self;
[self.view addSubview:tableView];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return @"Array and Tableview";
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return mArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
}
cell.textLabel.text = [mArray objectAtIndex:indexPath.row];
return cell;
}
- (void)dealloc
{
[mArray release];
[mDictionary release];
[mDictionary2 release];
[super dealloc];
}
@end
If you try to assign the some text to the cell’s textlabel the object returned from:
should be a string and not a whole dictionary.
When you just put the whole dictionary in the array
[mArray objectAtIndex:indexPath.row];will return a dictionary and you cannot assign a dictionary to the textlabel so you get an exception. If you want to store the whole dictionary useobjectForKeyto get the string you want:btw, you are not using ARC zo you probably want to get an autoreleased UITableViewCell so add
autoreleaseto you cell:or