1

新手问题在这里...

我使用 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 将加载而不会出现错误。我显然做错了什么,但我无法终生弄清楚它是什么。有人愿意为我指出显而易见的事情吗?

4

1 回答 1

4

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

但似乎你不想要静态内容。所以你只需要进入情节提要,选择 UITableView,进入 Attributes Inspector,然后将 Content type 更改为 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;
}

希望有帮助。

于 2011-12-07T06:28:29.070 回答