新手问题在这里...
我使用 ARC 和 Storyboard 在 Xcode 4.2 中创建了一个主从应用程序项目。我已将模板修改为:
主视图控制器.h
#import <UIKit/UIKit.h>
@class DetailViewController;
@interface MasterViewController : UITableViewController
{
NSMutableArray *items;
}
@property (strong, nonatomic) DetailViewController *detailViewController;
@property (strong, nonatomic) NSMutableArray *items;
@end
MasterViewController.m (snipits)
....
@synthesize items;
....
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.detailViewController = (DetailViewController)[[self.splitViewController.viewControllers lastObject] topViewController];
items = [[NSMutableArray alloc] initWithObjects:@"item 1", @"item 2", nil];
[self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionMiddle];
}
....
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [items count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return @"Test Section";
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell.
cell.textLabel.text = [items objectAtIndex:indexPath.row];
return cell;
}
当程序运行时,此代码将在此行失败:
[self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionMiddle];
除了这个例外:
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
如果我将列表(项目)缩减为单个项目,则 MasterViewController 将加载而不会出现错误。我显然做错了什么,但我无法终生弄清楚它是什么。有人愿意为我指出显而易见的事情吗?