iphone sdk выходит за рамки NSException

У меня есть «Завершение работы приложения из-за необработанного исключения« NSRangeException », причина:« *** -[NSArray objectAtIndex:]: индекс 24 за пределами [0 .. 23] »» Я не знаю, как поместить свой файл . м здесь, не будучи очень длинным. Пожалуйста, дайте мне знать, как я могу помочь решить эту проблему. Заранее спасибо!

код:

#import "RootViewController.h"
#import "FSDAppDelegate.h"
#import "DetailViewController.h"
@implementation RootViewController

#pragma mark -
#pragma mark Synthesizers

@synthesize mainTableView;
@synthesize contentsList;
@synthesize descArray;
@synthesize bannerImages;
@synthesize childController;
@synthesize searchResults;
@synthesize savedSearchTerm;


#pragma mark -
#pragma mark View methods

- (void)viewDidLoad
{
   NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);


    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Descriptions" ofType:@"plist"];

    NSArray *desc = [[NSArray alloc] initWithContentsOfFile:filePath];
    self.descArray = desc;
    [desc release];

    UIImage *texas = [UIImage imageNamed:@"1andtexas.jpg"];
    UIImage *cali = [UIImage imageNamed:@"2andcalifornia.jpg"];
    UIImage *ny = [UIImage imageNamed:@"3andnewyork.jpg"];
    UIImage *tmark = [UIImage imageNamed:@"1Tmark.jpg"];
    UIImage *walkie = [UIImage imageNamed:@"Walkietalkie.jpg"];
    UIImage *onekh = [UIImage imageNamed:@"Tracingpaper.jpg"];
    UIImage *onetwonine = [UIImage imageNamed:@"diffusion.jpg"];
    UIImage *greycard = [UIImage imageNamed:@"Greycard.jpg"];
    UIImage *oneeighty = [UIImage imageNamed:@"Oneeighty.jpg"];
    UIImage *two = [UIImage imageNamed:@"Two.jpg"];
    UIImage *twofourteen = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofifteen = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twosixteen = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twotwenty = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twotwentynine = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofifty = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftyone = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftytwo = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftythree = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftyfour = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftyfive = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftysix = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftyseven = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *twofiftyeight = [UIImage imageNamed:@"Diffusion.jpg"];
    UIImage *thirtytwohk = [UIImage imageNamed:@"3200k.jpg"];



    NSArray *banners = [[NSArray alloc] initWithObjects:
                        texas,
                        cali,
                        ny,
                        tmark,
                        walkie,
                        onekh,
                        onetwonine,
                        greycard,
                        oneeighty,
                        two,
                        twofourteen,
                        twofifteen,
                        twosixteen,
                        twotwenty,
                        twotwentynine,
                        twofifty,
                        twofiftyone,
                        twofiftytwo,
                        twofiftythree,
                        twofiftyfour,
                        twofiftyfive,
                        twofiftysix,
                        twofiftyseven,
                        twofiftyeight,
                        thirtytwohk,
                        nil];

    self.bannerImages = banners;

    [banners release];


    [super viewDidLoad];



    NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:
                             @"#1 or NUMBER ONE",
                             @"#2 or NUMBER TWO",
                             @"#3 or NUMBER THREE",
                             @"1 or ONE",
                             @"10-100,10-1,10-200,10-2,10-4 and 20",
                             @"1000H PAPER",
                             @"129 or HEAVY FROST",
                             @"18% GRAY or GREY CARD",
                             @"180 DEGREE RULE",
                             @"2 or TWO",
                             @"214 or FULL TOUGH SPUN",
                             @"215 or HALF TOUGH SPUN",
                             @"216 or FULL WHITE DIFFUSION",
                             @"220 or WHITE FROST",
                             @"229 or QUARTER TOUGH SPUN",
                             @"250 or HALF WHITE DIFFUSION",
                             @"251 or QUARTER WHITE DIFFUSION",
                             @"252 or EIGHTH WHITE DIFFUSION",
                             @"253 or FULL HAMPSHIRE",
                             @"254 or NEW HAMPSHIRE",
                             @"255 or HOLLYWOOD FROST",
                             @"256 or HALF HAMPSHIRE FROST",
                             @"257 or QUARTER HAMPSHIRE FROST",
                             @"258 or EIGHTH HAMPSHIRE FROST",
                             @"3200K or TUNGSTEN",
                             nil];
    [self setContentsList:array];
    [array release], array = nil;

    if ([self savedSearchTerm])
    {
        [[[self searchDisplayController] searchBar] setText:[self savedSearchTerm]];
    }

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

- (void)viewWillAppear:(BOOL)animated
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    [super viewWillAppear:animated];

    [[self mainTableView] reloadData];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

#pragma mark -
#pragma mark Table view datasource methods

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {

    NSMutableArray *toBeReturned = [[NSMutableArray alloc]init];
    for(char c = 'A'; c <= 'Z'; c++) [toBeReturned addObject:[NSString stringWithFormat:@"%c",c]];
    return toBeReturned;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    NSInteger rows;

    if (tableView == [[self searchDisplayController] searchResultsTableView])
        rows = [[self searchResults] count];
    else
        rows = [[self contentsList] count];

    return [contentsList count];
    return rows;

    NSLog(@"rows is: %d", rows);
    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

-(UITableViewCell *) tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    NSInteger row = [indexPath row];
    NSString *contentForThisRow = nil;

    if (tableView == [[self searchDisplayController] searchResultsTableView])
        contentForThisRow = [[self searchResults] objectAtIndex:row];
    else
        contentForThisRow = [[self contentsList] objectAtIndex:row];

    static NSString *CellIdentifier = @"CellIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    [[cell textLabel] setText:contentForThisRow];

    cell.textLabel.text = [contentsList objectAtIndex:indexPath.row];

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);

    return cell;
}

#pragma mark -
#pragma mark Table view delegate methods

-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

-(NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
    return @"Film Set Decipher";
}

-(void) tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    FSDAppDelegate *delegate = (FSDAppDelegate *)[[UIApplication sharedApplication] delegate];
    DetailViewController *detailVC = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
    detailVC.banner = [bannerImages objectAtIndex:indexPath.row];
    detailVC.description = [descArray objectAtIndex:indexPath.row];
    detailVC.title = [contentsList objectAtIndex:indexPath.row];
    self.childController = detailVC;
    [delegate.navigationController pushViewController:childController animated:YES];

    [detailVC release];

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

#pragma mark -
#pragma mark UISearchDisplayController Delegate Methods

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller 
shouldReloadTableForSearchString:(NSString *)searchString
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    [self handleSearchForTerm:searchString];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
    return YES;
}

- (void)searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    [self setSavedSearchTerm:nil];

    [[self mainTableView] reloadData];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}
#pragma mark -
#pragma mark Memory Management

- (void)didReceiveMemoryWarning {
    NSLog(@"Memory warning!");
    [super didReceiveMemoryWarning];
}
- (void)dealloc
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    [mainTableView release]; mainTableView = nil;
    [contentsList release]; contentsList = nil;
    [descArray release]; descArray = nil;
    [bannerImages release]; bannerImages = nil;
    [childController release]; childController = nil;
    [searchResults release], searchResults = nil;
    [savedSearchTerm release], savedSearchTerm = nil;

    [super dealloc];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

- (void)viewDidUnload {
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    self.mainTableView = nil;
    self.contentsList = nil;
    self.descArray = nil;
    self.bannerImages = nil;
    self.childController = nil;

    [super viewDidUnload];

    [self setSavedSearchTerm:[[[self searchDisplayController] searchBar] text]];

    [self setSearchResults:nil];

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);

}

- (void)handleSearchForTerm:(NSString *)searchTerm
{
    NSLog(@">>> Entering %s <<<", __PRETTY_FUNCTION__);

    [self setSavedSearchTerm:searchTerm];

    if ([self searchResults] == nil)
    {
        NSMutableArray *array = [[NSMutableArray alloc] init];
        [self setSearchResults:array];
        [array release], array = nil;
    }

    [[self searchResults] removeAllObjects];

    if ([[self savedSearchTerm] length] != 0)
    {
        for (NSString *currentString in [self contentsList])
        {
            if ([currentString rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location != NSNotFound)
            {
                [[self searchResults] addObject:currentString];
            }
        }
    }

    NSLog(@"<<< Leaving %s >>>", __PRETTY_FUNCTION__);
}

@end

Оказалось, проблема заключалась в том, что не все изображения были скопированы в папку Target>Copy Bundle Resources, и это приводило к сбою!?!? Огромное спасибо!


person Draken182    schedule 30.11.2010    source источник
comment
Можете ли вы правильно отформатировать код, пожалуйста. Так будет намного проще обнаружить проблему.   -  person Firoze Lafeer    schedule 30.11.2010


Ответы (2)


Ошибка говорит о том, что в массиве 24 элемента, а вы пытаетесь получить доступ к 25-му элементу. Поэтому вам нужно опубликовать код, который пытается получить доступ к 25-му элементу. Или выясните, почему он пытается найти 25-й элемент в массиве из 24 элементов.

РЕДАКТИРОВАТЬ:

Вы должны установить точку останова примерно в первой строке tableView:didSelectRowAtIndexPath:

затем в командной строке gdb> введите:

po descArray

Или просто:

p(int) [descArray count]

ИЛИ просмотрите панель переменных, чтобы увидеть, сколько элементов на самом деле находится в descArray в этот момент. При необходимости повторите для двух других массивов.

ИЗМЕНИТЬ СНОВА:

У вас есть другая проблема (возможно, не связанная) в нашем tableView:numberOfRowsInSection:

Вы все время возвращаете счетчик contentList. Строки после этого возврата, включая NSLogs, никогда не будут достигнуты. Как только вы нажмете этот первый возврат в C, вы немедленно вернетесь из этого метода. Я не думаю, что это ваша непосредственная проблема, но это другая проблема, которая возникнет, когда вы начнете настраивать поиск.

person Firoze Lafeer    schedule 30.11.2010
comment
Я запустил отладчик, чтобы увидеть, что это было, и вот что выскочило: - person Draken182; 30.11.2010
comment
0x9515116C <+0000> mov $ 0xc0025,% eax 0x95151171 <+0005> Вызов 0x950f03d8 <_sysenter_trap> 0x95151176 <+0010> JAE 0x95151186 <__ kill + 26> 0x95151178 <+0012> Вызов 0x9515117D <__ kill + 17> 0x9515117D <+0017> pop %edx 0x9515117e ‹+0018› mov 0xb4ef767(%edx),%edx 0x95151184 ‹+0024› jmp *%edx 0x95151186 ‹+0026› ret - person Draken182; 30.11.2010
comment
как выглядит трассировка стека? Это скажет вам, где происходит этот сбой. Затем вам нужно опубликовать этот код, чтобы кто-то мог вам помочь. - person Firoze Lafeer; 30.11.2010
comment
тьфу, осмелюсь спросить, как мне получить трассировку стека? - person Draken182; 30.11.2010
comment
Трассировка стека обычно находится в левом верхнем углу экрана отладчика. Или в приглашении gdb› вы можете ввести «bt». В вашей таблице 25 или более строк? Похоже, что вы это делаете, и в bannerImages, descArray или ContentList есть только 24 элемента. - person Firoze Lafeer; 30.11.2010
comment
Извините, мой предыдущий комментарий о том, где найти трассировку стека, предполагал, что вы нарушаете objc_exception_throw. Если нет, то стек вызовов должен был быть выложен прямо на консоль, чтобы вы могли найти его там. - person Firoze Lafeer; 30.11.2010
comment
k, поэтому происходит сбой в tableView:didSelectRowAtIndexPath:. Я предполагаю, что код, который вы разместили, взят из этого метода (похоже, что это так). Знаете ли вы, как установить условную точку останова в Xcode? Если не просто установить обычную точку останова в этом методе, а затем проверить размер каждого из этих трех массивов. Также, пожалуйста, покажите нам, как выглядит ваш tableView:numberOfRowsInSection:. - person Firoze Lafeer; 30.11.2010
comment
Строка NSInteger = [строка indexPath]; - person Draken182; 30.11.2010
comment
Где вы поставили точку останова? И что вы имеете в виду, что он вернулся с? Вы поставили точку останова в tableView:didSelectRowAtIndexPath:? И вы проверяли размер этих массивов в тот момент? - person Firoze Lafeer; 30.11.2010
comment
хорошо, я собираюсь предположить, что в descArray отсутствует 25-й элемент. Дважды проверьте этот plist. Кроме того, другая проблема, но вы не хотите выпускать все эти баннерные изображения в viewDidLoad. [UIImage imageNamed:] вернет те изображения, которые уже были автоматически выпущены. - person Firoze Lafeer; 30.11.2010
comment
Хорошо, я добавил точку останова в правильное tableView:didSelectRowAtIndexPath, и он сказал: Uncaught Exception: -[NSCFBoolean length]: нераспознанный селектор отправлен экземпляру 0x7fff706df280 Backtrace стека: трассировка стека была зарегистрирована на консоли. - person Draken182; 30.11.2010
comment
descArray, который представляет собой список описаний, имеет 0-24, всего 25 заполненных элементов. - person Draken182; 30.11.2010
comment
Я собираюсь отредактировать свой ответ, так как эти комментарии становятся очень длинными. - person Firoze Lafeer; 30.11.2010
comment
просто удалил все выпущенные изображения, а также - person Draken182; 30.11.2010
comment
Я добавил больше комментариев к своему ответу. - person Firoze Lafeer; 30.11.2010
comment
(gdb) p(int) [число массивов_описаний] $1 = 25 Текущий язык: auto; в настоящее время цель-c - person Draken182; 30.11.2010

Проверить количество объектов в этих bannerImages descArraycontentsList

эти массивы не имеют количество объектов, равное количеству строк в табличном представлении.

(Вы должны проверить, правильно ли вы подготавливаете свои массивы, а затем источник данных tableview и методы делегирования). Или поместите весь код здесь, если вы не получили решение.

person Ishu    schedule 30.11.2010