我的表格视图中填充了一些单元格,这些单元格显示了具有名称,价格和品牌的项目。我从Web服务获得的一些对象返回,在表视图单元格上看起来很丑。我不想填充价格为“ null”的表视图单元格。到目前为止,这是我的代码。现在,我将其更改为“价格不可用”。
for (NSDictionary *objItem in resultsArray)
{
NSString *currentItemName = [objectTitlesArray objectAtIndex:indexPath.row];
if ([currentItemName isEqualToString:objItem[@"title"]])
{
if (cell.priceLabel.text != (id)[NSNull null] && cell.priceLabel.text.length != 0 && cell.brandLabel.text != (id)[NSNull null] && cell.brandLabel.text.length != 0)
{
cell.nameLabel.text = currentItemName;
NSDictionary *bestPageDictionary = objItem[@"best_page"];
NSNumber *price = bestPageDictionary[@"price"];
if ((cell.priceLabel.text = @"<null>"))
{
cell.priceLabel.text = @"Price Unavailable";
}
else
{
cell.priceLabel.text = [NSString stringWithFormat:@"$%@", price];
}
NSArray *brandsArray = objItem[@"brands"];
cell.brandLabel.text = [brandsArray firstObject];
}
}
}
这是非常低效的。您要在字典中保留JSON(我假设是)返回值,然后为正在创建的每个单元循环字典。不仅如此,您还没有提前清理JSON。
创建一个无用的单元格然后回去尝试删除它要昂贵得多。在您的numberOfRowsInSection
代表中,您已经告诉过tableview
您X多个单元格。现在,您正在尝试删除将使回调弄乱的单元格。您必须创建一个方法,该方法将在完成所有单元的创建之后运行,然后将循环所有单元以将它们从tableView中删除,然后将其调用[table reloadData]
。但是,由于实际上并未从中删除数据,因此NSDictionary
实际上您将再次创建相同数量的单元格并陷入无限循环。
解决方案:
首先,更改您的结构。获得JSON返回值后,请对其进行清理以删除所有没有价格的值。我建议还使用一个对象类来保存每个服务器对象。这将大大简化TableView以及其他类的代码。现在您已经清理了退货,请将其从更改NSDictionary
为NSMutableArray
。然后numberOfRowsInSection:
打给你[array count]
。在cellForRowAtIndexPath:
您看来,只是[array objectAtIndex:indexPath.row]
为了得到您的对象。
您将希望代码大致如下所示:
ServerItem.h : NSObject{
@property (nonatomic,retain) NSString* name;
...
add in other properties here
}
- (NSMutableArray *) parseJSON:(NSDictionary *)jsonDict{
NSMutableArray *returnArray = [NSMutableArray array];
NSArray *dictArray = [NSArray arrayWithArray:jsonDict[@"results"]];
for (NSDictionary *itemDict in dictArray)
{
NSDictionary *bestPageDictionary = objItem[@"best_page"];
if (![bestPageDictionary[@"price"] isEqualToString:@"<null>"]])
{
ServerItem item = [ServerItem new];
item.price = ...
item.name = ....
[returnArray addObject:item];
}
}
return returnArray;
}
在您的webService代码中:
self.itemArray = [self parseJSON:dataDictionary];
然后
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.itemCallArray count]
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
...
ServerItem *cellItem = [self.itemsArray objectAtIndex:indexPath.row];
cell.nameLabel.text = cellItem.name;
cell.priceLabel.text = cellItem.price;
...
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句