2014-03-04 40 views
0

我想让我的NSdictionary值到UITableViewCell中。这是我的字典格式:NSDictionary allkeys到UITableViewCell

{ 
date = "3/4/14, 3:33:01 PM Pacific Standard Time"; 
weight = 244; 
} 

这是我用来填充我的uitableview(这是不工作)的代码。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
static NSString *simpleTableIdentifier = @"WeightCell"; 

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier]; 

if (cell == nil) { 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier]; 
} 


NSArray* allKeys = [weights allKeys]; 

NSDictionary *obj = [allKeys objectAtIndex: indexPath.row]; 

cell.textLabel.text = [obj objectForKey: @"date"]; 
cell.detailTextLabel.text = [obj objectForKey:@"weight"]; 

return cell; 
} 
+0

定义“不工作”。出了什么问题。请记住,字典没有顺序。这两个键每次都可以按不同顺序排列。 – rmaddy

+0

好的。通过不工作,我没有得到的tableview填充我的字典'权重'的数据。也许我不是那么正确的方式。 – TerryG

+0

您正在使用字典对象作为另一个字典上另一个对象的关键字? – J2theC

回答

2

你应该尝试初始化了的tableView阵列中的tableView本身以外...沿

- (void)viewDidLoad 
{ 
[super viewDidLoad]; 

_allKeys = [[NSMutableArray alloc] initWithArray:[weights allKeys]]; 

} 

线的东西一旦你已经初始化的数据,你可以在整个过程中对其进行访问。还要找出你的tableview需要多少行。

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
return [_allKeys count]; 
} 

然后,当您将数组访问到字典时,它保留了行数并可以正确访问它。

NSDictionary *obj = [_allKeys objectAtIndex: indexPath.row]; 

cell.textLabel.text = [obj objectForKey: @"date"]; 
cell.detailTextLabel.text = [obj objectForKey:@"weight"]; 

从我所看到的字典不能在你indexPath.row访问数组因为你没有初始化你在的tableView使用它之前的任何地方的阵列。

希望有帮助,T

1

一些其他的海报有很好的建议。但是,该行:

NSDictionary *obj = [allKeys objectAtIndex: indexPath.row]; 

错误。 allKeys是字典键的数组,可能是字符串。

所以,你要这样的代码来代替:

NSString *thisKey = allKeys[indexPath.row]; 
NSDictionary *obj = weights[thisKey]; 

注意,我用的是新目标C文字语法。表达式weights[thisKey]相当于[weights objectForKey: thisKey]

1

我没有看到weights对象的定义。如果要继续将NSDictionary添加到数组中,则需要使用NSMutableArray,并且您可能希望将其设置为类@property。比方说,你加入这样的:

@property (strong, nonatomic) NSMutableArray *weights; 

然后在您的tableView:cellForRowAtIndexPath:方法你要得到NSDictionary使用self.weights[indexPath.row]对应于该线。在使用它之前也不要忘记实例化weights,否则它将返回nil并且不会添加任何对象。

P.S .:用户提供了一些上下文here,他可能需要的是核心数据。

相关问题