2

编程新手**

尝试从可变数组访问对象时出现“超出范围”的 NSRangeException。错误显示 objectAtIndex 的数字很长,但该数组当前只有三个对象。

这是错误消息:由于未捕获的异常 'NSRangeException' 导致应用程序终止,原因:' * -[__NSArrayM objectAtIndex:]: index 2147483647 beyond bounds [0 .. 2]'

我正在使用核心数据。

当我选择通过 Core Data 填充的 tableview 的第一行时,应用程序崩溃。

可变数组称为“allDates”。

似乎导致它的代码在这里的 prepareForSegue 方法中:

DateTableViewController.m 的一部分

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{

NSString *segueIdentifier = [segue identifier];
    if ([segueIdentifier isEqualToString:@"showDetails"])
    {
        NSManagedObjectContext *context = [self managedObjectContext];

        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Date"
                                                  inManagedObjectContext:context];
        [fetchRequest setEntity:entity];


        self.allDates = [[context executeFetchRequest:fetchRequest error:nil] mutableCopy];
        DateIdeaDetailViewController *vc = [segue destinationViewController];

        NSIndexPath *selectedRowIndexPath = [self.tableView indexPathForSelectedRow];

         NSUInteger index = [allDates indexOfObject:selectedRowIndexPath];
        //edited based on WilliamFalcon added "(int)"
        _string = [NSMutableString stringWithFormat:@"%@", [allDates[(int)index] valueForKey:@"date_idea"]];

       vc.dateIdeaLabelText = self.string;

    }

}

日期表视图控制器.h

#import <UIKit/UIKit.h>
#import "LifeBook.h"
#import "LifeBookAppDelegate.h"
#import "DateIdeaDetailViewController.h"

@interface DateTableViewController : UITableViewController 

@property (strong, nonatomic) NSMutableArray *allDates;
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
@property (weak, nonatomic) IBOutlet UITableViewCell *tableViewCell1;
@property (strong, nonatomic) NSMutableString *string;

@property (strong, nonatomic) NSString *label;


@end

如果这是一个愚蠢的问题,请告诉我。任何类型的资源都值得赞赏。

谢谢你的帮助

4

2 回答 2

2

indexOfObject:回归的事实2147483647并非侥幸。2147483647等价于NSNotFound等价于NSIntegerMax,这是indexOfObject:当您指定的对象在数组中的任何索引处都不存在时返回的值,或者换句话说,“未找到”。

文档

对应数组值等于 anObject 的最低索引。如果数组中没有一个对象等于 anObject,则返回 NSNotFound。

这可以帮助我们了解您的应用程序崩溃的原因。您显然无法访问数组中任何比数组计数小一的索引处的元素,并且2147483647该数字比数组的计数大得多,这会导致引发范围异常。幸运的是,这个问题很容易解决,您所要做的就是在索引大于或等于数组的计数时防止对数组的访问。这是一个例子:

if (index < allDates.count) {
    _string = [NSMutableString stringWithFormat:@"%@", [allDates[(int)index] valueForKey:@"date_idea"]];
   vc.dateIdeaLabelText = self.string;
}else{
    // do something else..
    vs.dateIdeaLabelText = @"Something went wrong!";
}
于 2013-11-11T03:36:47.183 回答
1

看起来您正在向数组询问 indexpath 的索引。我不认为这是一组索引路径......

你应该只做 allDates[selectedRowIndexPath.row]。

还要尝试将该行分解为多个部分,以便更好地调试。

于 2013-11-11T03:55:19.603 回答