我正在拆分字符串:
@"Sam|26|Developer,Hannah|22|Team Leader,Max|1|Dog"
并使用NSMutableDictionary在带有3个标签的TableViewCell中显示。代码:
- (void)viewDidLoad {
[super viewDidLoad];
NSString *test = @"Sam Parrish|26|Developer,Hannah Rajamets|22|Team Leader,Max Parrish|1|Dog";
testArray = [[NSArray alloc] init];
testArray = [test componentsSeparatedByString:@","];
dict = [NSMutableDictionary dictionary];
for (NSString *s in testArray) {
testArrayNew = [s componentsSeparatedByString:@"|"];
[dict setObject:[testArrayNew objectAtIndex:1] forKey:[testArrayNew objectAtIndex:0]];
[dict setObject:[testArrayNew objectAtIndex:2] forKey:[testArrayNew objectAtIndex:1]];
NSLog(@"Dictionary: %@", [dict description]);
}
[dict retain];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[dict allKeys] count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"CustomCell";
untitled *cell = (untitled *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"untitled" owner:nil options:nil];
for (id currentObject in topLevelObjects) {
if ([currentObject isKindOfClass:[UITableViewCell class]]) {
cell = (untitled *) currentObject;
break;
}
}
}
// Configure the cell.
cell.nameLabel.text = [[dict allKeys] objectAtIndex:[indexPath row]];
cell.ageLabel.text = [dict objectForKey:cell.nameLabel.text];
cell.jobLabel.text = [dict objectForKey:cell.ageLabel.text];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
当我运行时显示6个TableViewCells,其中3个是完美的,另外3个是各种各样的数据。我意识到这与setObject: forKey:
有关,但似乎无法找到解决方案以使其正常工作。
任何帮助非常感谢..
SAM
答案 0 :(得分:0)
我会将数据存储为持有NSArrays的NSArray ....
- (void)viewDidLoad {
[super viewDidLoad];
NSString *test = @"Sam Parrish|26|Developer,Hannah Rajamets|22|Team Leader,Max Parrish|1|Dog";
data = [[NSMutableArray alloc] init];
for (NSString *s in testArray) {
[data addObject:[s componentsSeparatedByString:@"|"]];
}
}
然后在
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
使用
// Configure the cell.
NSArray *cellData = [data objectAtIndex:indexPath.row];
cell.nameLabel.text = [cellData objectAtIndex:0];
cell.ageLabel.text = [cellData objectAtIndex:1];
cell.jobLabel.text = [cellData objectAtIndex:2];
答案 1 :(得分:0)
如果我理解正确的话,你说前三个单元格是正确的,其他三个单元格根本不显示?如果是这样的话,那就是问题:
return [[dict allKeys] count];
不应该......
return [testArray count];
...在这种情况下,您需要保留testArray
。
此外,您有内存泄漏。您创建了NSArray
的实例,然后通过将componentsSeparatedByString:
的返回值分配给同一个变量来立即泄漏它。您是否在代码上运行静态分析器?