iOS Xcode 4.2主 – 详细信息应用程序模板抛出NSRangeException

新手问题在这里……

我使用ARC和Storyboard在Xcode 4.2中创建了一个Master-Detail应用程序项目。 我已将模板修改为:

MasterViewController.h

#import  @class DetailViewController; @interface MasterViewController : UITableViewController { NSMutableArray *items; } @property (strong, nonatomic) DetailViewController *detailViewController; @property (strong, nonatomic) NSMutableArray *items; @end 

MasterViewController.m(剪辑)

 .... @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将加载没有错误。 我显然做错了什么,但我不能为我的生活弄清楚它是什么。 有人关心为我指出明显的事吗?

该模板包括为静态单元格设置的UITableView。 它实际上是一个静态单元格。 (这就是为什么让你的arrays长一个项目的工作)

但似乎你不想要静态内容。 因此,您只需进入故事板,选择UITableView,转到Attributes Inspector,然后将Content类型更改为Dynamic Prototypes。

这应该让你超越这个问题。

编辑

一个有点相关的问题是您可能还想在故事板中使用原型单元格。 为此,只需将该原型的单元格标识符设置为您在tableView中使用的单元格标识符:cellForRowAtIndexPath:。

然后省略整个’if(cell == nil)’部分。 细胞不会是零。

所以这个方法现在看起来像这样:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; // <-- Make sure this matches what you have in the storyboard UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; // Configure the cell. cell.textLabel.text = [self.items objectAtIndex:indexPath.row]; return cell; } 

希望有所帮助。