【发布时间】:2012-03-24 16:15:11
【问题描述】:
我在表格中选择行时遇到问题。
当我选择任何行或尝试滚动表格时,我得到 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
【问题讨论】:
-
你的代码有很多问题!请阅读一些介绍性的东西。例如,您的命名会导致代码不可读。然后您将单元格出列,并在下一行中创建一个新单元格。为什么?这没有任何意义。而这个
!(indexPath.row >= [self.FoodsArray count])肯定不是你想要做的。 -
你认为
[Food new]在做什么? -
好吧,他的代码肯定有问题。但是
!(indexPath.row >= [self.FoodsArray count])等价于(indexPath.row < [self.FoodsArray count])是绝对正确的,而[Food new]是[[Food alloc] init]的缩写 -
你能发布堆栈跟踪吗?当崩溃发生时,Xcode 中的控制台应该会显示出问题的确切位置和位置。如果您可以发布它,我们可以为您提供帮助。