cellForRowAtIndexPath返回空值

我正在一个应用程序工作,我有一个UITableView填充与方法tableView:cellForRowAtIndexPath:一个NSMutableArray,它工作正常,但问题是,我想改变图像的tableViewCell,当我尝试访问单元格它总是返回null。 我在这里给代码,请告诉我,我是否错过了一些东西…

在viewController.h文件中

@interface DevicesViewController : UIViewController{ IBOutlet UITableView *deviceTableVIew; NSMutableArray *devicesArray; NSMutableArray *deviceDetailArray; } @property (nonatomic,retain) IBOutlet UITableView *deviceTableVIew; @property (nonatomic,retain) NSMutableArray *devicesArray; @property (nonatomic,retain) NSMutableArray *deviceDetailArray; -(IBAction)setDevicesOn:(id)sender; -(IBAction)setDevicesOff:(id)sender; @end 

在视图controller.m文件中

  -(IBAction)setDevicesOn:(id)sender{ UITableViewCell *cell = [deviceTableVIew cellForRowAtIndexPath:[NSIndexPath indexPathForRow:3 inSection:1]]; cell.imageView.image = [UIImage imageNamed:@"device-on-image.png"]; [deviceTableVIew reloadData]; ... } -(IBAction)setDevicesOff:(id)sender{ UITableViewCell *cell = [deviceTableVIew cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]]; cell.imageView.image = [UIImage imageNamed:@"device-off-image.png"]; [deviceTableVIew reloadData]; ... } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [devicesArray count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; } cell.textLabel.text = [devicesArray objectAtIndex:indexPath.row]; cell.detailTextLabel.text = [deviceDetailArray objectAtIndex:indexPath.row]; cell.imageView.image = [UIImage imageNamed:@"device-off-image.png"]; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; return cell; } 

你的UITableViewDataSource(你的viewController)告诉tableView它只有一个部分。

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } 

在您的setDevicesOff:方法中,您正在使用一节为1的indexPath。
由于第一部分的索引为0,因此第一部分的indexPath尝试引用tableView中的第二部分。 你的tableView没有该部分,并返回零,因为这一点。

尝试这个:

 -(IBAction)setDevicesOff:(id)sender{ UITableViewCell *cell = [deviceTableVIew cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]; cell.imageView.image = [UIImage imageNamed:@"device-off-image.png"]; //[deviceTableVIew reloadData]; this shouldn't be necessary ... } 

我想你还没有宣布你的viewController作为tableview委托和tableview数据源。

 @interface DevicesViewController : UIViewController<UITableViewDataSource,UITableViewDelegate> 

我看不到.m文件,但是我认为你已经为表格视图设置了委托和数据源。 请检查所有这些事情和代码将正常工作。

希望这会帮助你。