cellForRowAtIndexPath返回null值

Has*_*sam 1 iphone uitableview ios xcode4.2

我正在开发一个应用程序,我有一个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
Run Code Online (Sandbox Code Playgroud)

在视图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;
    }
Run Code Online (Sandbox Code Playgroud)

Mat*_*uch 5

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

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

在您的setDevicesOff:方法中,您使用的索引为1,
因为第一部分的索引为0,indexPath的第1部分尝试引用tableView中的第二部分.你的tableView没有那个部分,因此返回nil.

试试这个:

-(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
    ...
}
Run Code Online (Sandbox Code Playgroud)