我已經創建了一個數組,兩個字典和一個tableview。 tableview應顯示數組的內容,該數組包含字典的數據。當我嘗試顯示它使用「[mArray addObject:(mDictionary)];」它拋出一個異常,但如果我使用「[mArray addObject:[mDictionary objectForKey:@」firstname「]];」它的工作正常。在表格視圖中顯示數組和字典值
你能幫我理解爲什麼會發生這種情況嗎?如果不使用「objectForKey」就不能顯示字典值?
這是我的「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
這意味着如果沒有使用鍵值我們不能顯示字典數據? – Newbee
是的,並使用'objectForKey'來獲取正確的NSString對象。那麼......你也可以使用字典的描述爲textlabel如果這是你想要的:'[[mArray objectAtIndex:indexPath.row] description];' – Tieme