我使用以下代码将数据加载到tableview中。以下是我的代码,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = nil;
cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"any-cell"];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:@"any-cell"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.layer.borderWidth = 1.0;
cell.layer.cornerRadius = 10;
cell.layer.borderColor = [UIColor blackColor].CGColor;
UILabel* productAmountTextLabel = [[UILabel alloc]init];
productAmountTextLabel.font = [UIFont fontWithName:@"HelveticaNeue" size:10];
productAmountTextLabel.frame = CGRectMake(0, 0, 100, 30); // for example
productAmountTextLabel.tag = 10000; // any number
[cell.contentView addSubview:productAmountTextLabel];
}
UILabel* lbl = (UILabel*)[cell.contentView viewWithTag: 10000];
NSManagedObject *device = [self.devices objectAtIndex:indexPath.row];
lbl.text = [device valueForKey:@"amount"];
return cell;
}
问题是tableview的每个单元格显示相同的值。为什么呢?
以下是我的viewdDidLoad方法,
- (void)viewDidLoad
{
segmentedControl = [[URBSegmentedControl alloc]initWithTitles:titles icons:icons];
NSError *Error = nil;
APIRequest *apiRequest = [[APIRequest alloc]init];
[apiRequest getPendingData];
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"PendingShipmentDetails"];
self.devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"PendingShipmentDetails" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&Error];
amountArray = [[NSMutableArray alloc] init];
for (NSManagedObjectContext * info in fetchedObjects)
{
[amountArray addObject:[info valueForKey:@"amount"]];
}
segmentedControl.segmentBackgroundColor = [UIColor colorWithRed:86/255.0f green:199/255.0f blue:188/255.0f alpha:1];
[segmentedControl addTarget:self action:@selector(handleSelection:) forControlEvents:UIControlEventValueChanged];
NSLog(@"%@",self.devices);
self.completedOrdersTableView.hidden = YES;
[self.view addSubview:segmentedControl];
[super viewDidLoad];
}
我在那边获取值并将其添加到数组中。
在
viewDidLoad
中,它具有唯一的数据集,但是在cellForRowAtIndexPath
中,它具有相同的数据集,重复多次。 最佳答案
感谢Michaël Azevedo帮助我调试问题。我调试的方式是,我尝试记录indexpath.row和indexpath.section。我注意到,行始终为0,部分为动态(值更改)。
在cellForRowAtIndexPath
中,我参考indexpath.row设置值,该值始终为0。
然后我按如下方式更改了代码,
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.devices count];
}
所以现在
numberOfRowsInSection
不再为零。因此,在访问它时,它将不会多次获取同一组值。