我有一个NSDictionary的NSArray:
因此,我的数组被称为messagesArray,它实际上是一个字典数组,因为我必须使用字典方法按发件人名称对消息进行排序。
以下是我的消息数组:
{
MessageBody1 = nmnmn;
MessageBody2 = kkkjk;
MessageBody3 = hbjhbjbb;
MessageBody4 = "Kjnhkbjhbjh ";
MessageBody5 = "N m jbjbhb";
MessageBody6 = "";
MessageBody7 = "Test test test";
MessageBody8 = "";
MessageBody9 = "This is a test.";
senderName = testUser;
}
考虑到每个键递增1,我如何用所有"MessageBody"键填充表视图?
首先,您说过发布了messagesArray
的代码,但数组应该用括号( )
包围,而不是用大括号{ }
(大括号用于字典)包围,但我认为这是拼写错误。
您应该使用表视图的indexPath
来在cellForRowAtIndexPath:
中获得正确的对象。类似这样的东西:
cell.textLabel.text = messagesArray[indexPath.row];
然而,如果你的意思是messagesArray
是一个字典数组,而你发布的代码是字典的一个例子,那么没有一个很好的方法可以根据你的布局将每个MessageBody
分割成自己的单元格。相反,像这样的东西的正确布局应该是:
> messagesArray //holds all the messages
> msgArray //one for each message
> MessageBody strings (however many there are)
然后,可以返回messagesArray.count
表示表视图中的节数,返回[messagesArray[section] count]
表示给定节中的行数。
每个单元格的文本将类似于:
cell.textLabel.text = [messagesArray[indexPath.section] objectAtIndex:[indexPath.row]];
它似乎只是一个字典的数组,并且您希望(我认为)表中的值按键的数字部分排序。我们可以在数据源方法中争论这个问题,但将数据更改为数据源方法想要的数据会简单得多,即数组。。。
// add this in your class's private interface
@property(strong,nonatomic) NSMutableArray *datasourceArray;
NSDictionary *messagesArray = // your messagesArray that's really a dictionary
self.datasourceArray = [NSMutableArray array];
NSArray *keys = [[messagesArray allKeys] sortedArrayUsingSelector:@selector(compare:)];
for (NSString *key in keys) {
[datasourceArray addObject:dictionary[key]];
}
这从字典中获取键,按词汇对它们进行排序,然后获取每个值(按排序顺序)并将它们放入datasourceArray中。
现在,您的数据源方法将变得简单。。。
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.datasourceArray.count;
}
在cellForRowAtIndexPath
:中,使用查找您的单元格数据
NSString *message = self.datasourceArray[indexPath.row];