New*_*bee 2 objective-c nsmutablearray ios
我创建了一个数组,两个词典和一个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
Run Code Online (Sandbox Code Playgroud)
在.h文件中声明一个数组:
NSArray *keys
Run Code Online (Sandbox Code Playgroud)
在viewDidLoad中写这个
keys = [mDictionary allKeys];
Run Code Online (Sandbox Code Playgroud)
这在cellForRowAtIndexPath中
cell.textLabel.text = [mDictionary objectForKey:[keys objectAtIndex:indexPath.row];
Run Code Online (Sandbox Code Playgroud)