当我在UITableView中选择行时获取EXC_BAD_ACCESS

时间:2012-03-24 16:15:11

标签: objective-c uitableview

我在表格中选择行时遇到问题。

当我选择任何行或尝试滚动表格时,我得到了EXC_BAD_ACCESS。

我的观点非常简单。 用户按下按钮后,我创建了包含10个对象(Food类)的表。 Food是一个带有id和name的简单类。我有一个NSMutableArray,它包含了所有的主题。

感谢您的帮助!

代码:

@interface SearchFood : UIViewController <UITextFieldDelegate,   
UITableViewDataSource,    UITableViewDelegate>
{
    UITableView * foodsTable;
}

@property(nonatomic, retain) NSMutableArray *FoodsArray;

-(void)searchButtonClick:(id)sender;

@end


*************************************
import "SearchFood.h"
import "AppDelegate.h"
import "Food.h"

@implementation SearchFood

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.title = @"Search for food";
    self.view.backgroundColor = [UIColor whiteColor];

    btnSearch = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    [btnSearch setFrame:CGRectMake(220, 10,100, 40)];
    [btnSearch setTitle:@"Serach" forState:UIControlStateNormal];
    [btnSearch addTarget:self action:@selector(searchButtonClick:) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:btnSearch];
    [btnSearch release];

    Food *newfood = [Food new];
    newfood.Food_Name = @"guy";

    self.FoodsArray = [NSMutableArray arrayWithObjects:newfood, nil];
}


-(void)searchButtonClick:(id)sender
{
    foodsTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 80, 320, 460) 
    style:UITableViewStylePlain];


    foodsTable.dataSource = self;
    foodsTable.delegate = self;
    foodsTable.allowsSelection = YES;

    [self.view addSubview:foodsTable];
    [foodsTable release];

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.FoodsArray count];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *) indexPath {
    NSLog(@"Press row");
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"<#MyCell#>";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];

    if (!(indexPath.row >= [self.FoodsArray count]))
    {
        Food * currFood = (Food *)[self.FoodsArray objectAtIndex:indexPath.row];
        cell.textLabel.text = currFood.Food_Name;

        [cell setSelectionStyle:UITableViewCellSelectionStyleBlue];
    }

    return cell;
}

*********************
Food class:

@interface Food : NSObject


@property (nonatomic, retain) NSString* Food_ID;
@property ( nonatomic, retain )    NSString * Food_Name; 

@end

#import "Food.h"

@implementation Food
@synthesize Food_ID;
@synthesize Food_Name;

@end

1 个答案:

答案 0 :(得分:0)

如果第一次未启动此单元格,dequeueReusableCellWithIdentifier:将返回nil。因此,您无法继续使用不存在的单元格。