如何在tableview中显示字典数据

时间:2013-01-31 06:11:53

标签: ios objective-c nsmutabledictionary

我创建了一个数组,其数据显示在tableview中。现在我想将字典数据添加到该数组并在同一个tableview中显示它。我创建了一个按钮,它将字典值添加到数组中,但我无法在tableview中看到数据。

这是我的“ViewController.m”

#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
mArray = [[NSMutableArray alloc]initWithObjects:@"one",@"two",@"three",@"four",@"five",@"six",@"seven",@"eight",@"nine",@"ten", nil];
mDictionary = [[NSMutableDictionary alloc]init];
[mDictionary setValue:@"gfhhgfhf" forKey:@"firstname"];
[mDictionary setValue:@"hhgghf" forKey:@"lastname"];
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;
UIButton *button = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
button.frame = CGRectMake(200, 400, 100, 30);
[button setTitle:@"ADD" forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button addTarget:self action:@selector(addValueInArray) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:tableView];
[self.view addSubview:button];
}
-(void)addValueInArray{
[mArray addObject:(mDictionary)];
[mArray reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (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];
[super dealloc];
}
@end

2 个答案:

答案 0 :(得分:1)

使用此功能并替换您的功能。它会起作用

   -(void)addValueInArray{
   [mArray addObject:[[mDictionary objectForKey:@"firstname"]stringByAppendingString:[mDictionary objectForKey:@"lastname"]];
   [tableView reloadData];
    }

答案 1 :(得分:1)

您可以通过执行此操作填充mArray - >

-(void)addValueInArray{
   [[mArray addObject:[[mDictionary objectForKey:@"firstname"]stringByAppendingString:[mDictionary objectForKey:@"lastname"]]];
   [tableView reloadData];
    }

然后,在您的表格视图委托方法中,执行此操作 - >

- (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;
}

希望它有所帮助...