ios - *** 由于未捕获的异常 'NSRangeException' 而终止应用程序,原因 : '*** -[__NSArrayI objectAtIndex:]: index 3 beyond bounds [0 .. 2]'

标签 ios parsing nsarray sidebar nsexception

我已经找过其他类似的帖子,但没有一个能解决我的问题。我收到此错误:

*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 3 beyond bounds [0 .. 2]'

我正在使用菜单边栏在触摸侧边菜单按钮时显示菜单选项。

这是我的代码:

#import "SidebarViewController.h"
#import "PhotoViewController.h"
#import "SWRevealViewController.h"

@interface SidebarViewController ()

@property (nonatomic, strong) NSArray *menuItems;

@end

@implementation SidebarViewController


- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor colorWithWhite:0.2f alpha:1.0f];
    self.tableView.backgroundColor = [UIColor colorWithWhite:0.2f alpha:1.0f];
    self.tableView.separatorColor = [UIColor colorWithWhite:0.15f alpha:0.2f];

    _menuItems = @[@"title", @"news", @"comments", @"map", @"calendar", @"wishlist", @"bookmark", @"tag"];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) prepareForSegue: (UIStoryboardSegue *) segue sender: (id) sender
{
    // Set the title of navigation bar by using the menu items
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    UINavigationController *destViewController = (UINavigationController*)segue.destinationViewController;
    destViewController.title = [[_menuItems objectAtIndex:indexPath.row] capitalizedString];

    // Set the photo if it navigates to the PhotoView
    if ([segue.identifier isEqualToString:@"showPhoto"]) {
        PhotoViewController *photoController = (PhotoViewController*)segue.destinationViewController;
        NSString *photoFilename = [NSString stringWithFormat:@"%@_photo.jpg", [_menuItems objectAtIndex:indexPath.row]];
        photoController.photoFilename = photoFilename;
    }

    if ( [segue isKindOfClass: [SWRevealViewControllerSegue class]] ) {
        SWRevealViewControllerSegue *swSegue = (SWRevealViewControllerSegue*) segue;

        swSegue.performBlock = ^(SWRevealViewControllerSegue* rvc_segue, UIViewController* svc, UIViewController* dvc) {

            UINavigationController* navController = (UINavigationController*)self.revealViewController.frontViewController;
            [navController setViewControllers: @[dvc] animated: NO ];
            [self.revealViewController setFrontViewPosition: FrontViewPositionLeft animated: YES];
        };

    }

}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [self.menuItems count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = [self.menuItems objectAtIndex:indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    if (indexPath.section == 0) {
        NSArray *titles = @[@"Home", @"Profile", @"Chats"];
        cell.textLabel.text = titles[indexPath.row];
    } else {
        NSArray *titles = @[@"John Appleseed", @"John Doe", @"Test User"];
        cell.textLabel.text = titles[indexPath.row];
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{

    [cell setBackgroundColor:[UIColor colorWithWhite:0.2f alpha:1.0f]];

}

@end

这是堆栈:

    *** First throw call stack:
(
    0   CoreFoundation                      0x029ea1e4 __exceptionPreprocess + 180
    1   libobjc.A.dylib                     0x027698e5 objc_exception_throw + 44
    2   CoreFoundation                      0x0299e8b2 -[__NSArrayI objectAtIndex:] + 210
    3   CoreFoundation                      0x02a68f48 -[NSArray objectAtIndexedSubscript:] + 40
    4   Trixel                              0x00093fbc -[SidebarViewController tableView:cellForRowAtIndexPath:] + 572
    5   UIKit                               0x0131511f -[UITableView _createPreparedCellForGlobalRow:withIndexPath:] + 412
    6   UIKit                               0x013151f3 -[UITableView _createPreparedCellForGlobalRow:] + 69
    7   UIKit                               0x012f6ece -[UITableView _updateVisibleCellsNow:] + 2428
    8   UIKit                               0x0130b6a5 -[UITableView layoutSubviews] + 213
    9   UIKit                               0x0128b964 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 355
    10  libobjc.A.dylib                     0x0277b82b -[NSObject performSelector:withObject:] + 70
    11  QuartzCore                          0x001e145a -[CALayer layoutSublayers] + 148
    12  QuartzCore                          0x001d5244 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 380
    13  QuartzCore                          0x001d50b0 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 26
    14  QuartzCore                          0x0013b7fa _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 294
    15  QuartzCore                          0x0013cb85 _ZN2CA11Transaction6commitEv + 393
    16  QuartzCore                          0x001fa5b0 +[CATransaction flush] + 52
    17  UIKit                               0x0121a9bb _UIApplicationHandleEventQueue + 13095
    18  CoreFoundation                      0x0297377f __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 15
    19  CoreFoundation                      0x0297310b __CFRunLoopDoSources0 + 235
    20  CoreFoundation                      0x029901ae __CFRunLoopRun + 910
    21  CoreFoundation                      0x0298f9d3 CFRunLoopRunSpecific + 467
    22  CoreFoundation                      0x0298f7eb CFRunLoopRunInMode + 123
    23  GraphicsServices                    0x03dc75ee GSEventRunModal + 192
    24  GraphicsServices                    0x03dc742b GSEventRun + 104
    25  UIKit                               0x0121cf9b UIApplicationMain + 1225
    26  Trixel                              0x000a0b8d main + 141
    27  libdyld.dylib                       0x039e06d9 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

最佳答案

在您的 cellForRowAtIndexPath 中,您的代码需要 2 个部分,而您返回一个部分

做如下改动

- (void)viewDidLoad {
    //your code

    //section1 and 2 are ivars of type NSSArray
    section1 = @[@"Home", @"Profile", @"Chats"];
    section2 = @[@"John Appleseed", @"John Doe", @"Test User"];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    if (section == 0) {
    {
        return [section1 count];
    }
    else {
        return [section2 count];
    }
}

在你的cellForRowAtIndexPath

if (indexPath.section == 0) {
    cell.textLabel.text = section1[indexPath.row];
} else {
    cell.textLabel.text = section2[indexPath.row];
}

关于ios - *** 由于未捕获的异常 'NSRangeException' 而终止应用程序,原因 : '*** -[__NSArrayI objectAtIndex:]: index 3 beyond bounds [0 .. 2]' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25237994/

相关文章:

ios - 尝试从字典中检索字符串时出现 "[__NSArrayM objectForKey:]: unrecognized selector"

ios - 按委托(delegate)自动存储数据(swift)

ios - 使用 Swift 的 NSLocalization + Storyboard

ios - 我的应用程序有一个通配符应用程序 ID?

objective-c - iOS:发送短信

JavaScript 无法将印地语/阿拉伯数字转换为实数值变量

objective-c - NSArray 添加元素

objective-c - 使用 SearchBar 时出现 NSUnknownKeyException。此类不符合键名的键值编码

php - 如何创建包含html代码的json对象

使用 nom 解析驼峰式字符串