Nano Hash - криптовалюты, майнинг, программирование

NSInvalidArgumentException: [__NSArrayM insertObject:atIndex:]: объект не может быть нулевым [закрыт]

я создаю проект с приложением панели вкладок, базой данных и сегментированным элементом управления в управлении навигацией (программно) для отображения информации из базы данных, и я получаю SIGABRT с Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil' в окне консоли..

Делегат приложения TableView.

#import "SegmentsController.h"
#import "TableViewAppDelegate.h"
#import "RootViewController.h"
#import "AtoZHomePageViewController.h"
#import "CollectionRecipe.h"
#import "NSArray+PerformSelector.h" 

@interface TableViewAppDelegate()

- (NSArray *)segmentViewControllers;
- (void)firstUserExperience;
@end


@implementation TableViewAppDelegate

@synthesize window;
@synthesize navigationController;
@synthesize tabbarController;
@synthesize recipes;
@synthesize segmentsController, segmentedControl;


#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 

    NSArray * viewControllers = [self segmentViewControllers];
   // UINavigationController * navigationController = [[[UINavigationController alloc] init] autorelease];
    self.segmentsController = [[SegmentsController alloc] initWithNavigationController:navigationController viewControllers:viewControllers];

    self.segmentedControl = [[UISegmentedControl alloc] initWithItems:[viewControllers arrayByPerformingSelector:@selector(title)]];
    self.segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;

    [self.segmentedControl addTarget:self.segmentsController
                              action:@selector(indexDidChangeForSegmentedControl:)
                    forControlEvents:UIControlEventValueChanged];


    databaseName = @"RecipeDatabase.sql";

    // Get the path to the documents directory and append the databaseName
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDir = [documentPaths objectAtIndex:0];
    databasePath = [documentsDir stringByAppendingPathComponent:databaseName];

    // Execute the "checkAndCreateDatabase" function
    [self checkAndCreateDatabase];

    // Query the database for all animal records and construct the "animals" array
    [self readRecipesFromDatabase];

    // Configure and show the window
     [self firstUserExperience];
    [window addSubview:[tabbarController view]];
    [window addSubview:[navigationController view]];
    [window makeKeyAndVisible];
    return YES;
}

#pragma mark -
#pragma mark Segment Content

- (NSArray *)segmentViewControllers {
    UIViewController * AtoZRecipe     = [[AtoZHomePage alloc] initWithNibName:@"AtoZRecipeController" bundle:nil];
    UIViewController * RecipesCollection = [[CollectionRecipe alloc] initWithNibName:@"RecipeCollection" bundle:nil];

    NSArray * viewControllers = [NSArray arrayWithObjects:AtoZRecipe, RecipesCollection, nil];
    [AtoZRecipe release]; [RecipesCollection release];

    return viewControllers;
}

- (void)firstUserExperience {
    self.segmentedControl.selectedSegmentIndex = 0;
    [self.segmentsController indexDidChangeForSegmentedControl:self.segmentedControl];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Save data if appropriate
}
-(void) checkAndCreateDatabase{
    // Check if the SQL database has already been saved to the users phone, if not then copy it over
    BOOL success;

    // Create a FileManager object, we will use this to check the status
    // of the database and to copy it over if required
    NSFileManager *fileManager = [NSFileManager defaultManager];

    // Check if the database has already been created in the users filesystem
    success = [fileManager fileExistsAtPath:databasePath];

    // If the database already exists then return without doing anything
    if(success) return;

    // If not then proceed to copy the database from the application to the users filesystem

    // Get the path to the database in the application package
    NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];

    // Copy the database from the package to the users filesystem
    [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];


}

-(void) readRecipesFromDatabase {
    // Setup the database object
    sqlite3 *database;

    // Init the animals Array
    recipes = [[NSMutableArray alloc] init];

    // Open the database from the users filessytem
    if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
        // Setup the SQL Statement and compile it for faster access
        const char *sqlStatement = "select * from recipe order by name";
        sqlite3_stmt *compiledStatement;
        if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
            // Loop through the results and add them to the feeds array
            while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
                // Read the data from the result row
                NSString *aName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
                NSString *aAuthor=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,2)]; 
                NSString *aThumbnail=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,3)];
                NSString *aPre_time=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,5)];
                NSString *aBake_time=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,6)];
                NSString *aTota_ltime=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 7)];
                NSString *alarge_image=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,8)];                    
                NSString *asmall_image=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 9)]; 
                NSString *asummary=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 10)];
                NSString *aServe_size=[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,11)];
                // Create a new recipe object with the data from the database
               AtoZHomePage *recipe=[[AtoZHomePage alloc] initWithName:aName author:aAuthor img_thumbnail:aThumbnail pre_Time:aPre_time bake_Time:aBake_time total_time:aTota_ltime large_Img:alarge_image small_Img:asmall_image summary:asummary serve_size:aServe_size];
                  // Add the recipe object to the recipes Array
                [recipes addObject:recipe];

                [recipe release];
            }
        }
        // Release the compiled statement from memory
        sqlite3_finalize(compiledStatement);

    }
    sqlite3_close(database);    
}



#pragma mark -
#pragma mark Memory management

- (void)dealloc {
    self.segmentedControl   = nil;
    self.segmentsController = nil;
    [recipes release];
    [tabbarController release];
    [navigationController release];
    [window release];
    [super dealloc];
}

@end

эта строка неоднозначна NSArray * viewControllers = [NSArray arrayWithObjects:AtoZRecipe, RecipesCollection, nil];, поскольку я видел большинство связанных сообщений, и если я удалю nil, то будет отсутствовать дозорный, и, по моему мнению, я вызвал соответствующие контроллеры представления. Пожалуйста, помогите мне избавиться от этой ошибки... Заранее спасибо :) :)


  • [recipes addObject:recipe]; эта строка может быть первой, когда произошел сбой.. добавьте здесь точку останова.. в любом случае добавьте точки останова в свой курс во многих местах и ​​проверьте, какие функции успешно проходят.. 08.03.2012
  • Поместите точку останова в начале всех методов, и все они сообщат нам, где именно останавливается ваше приложение, что подскажет нам, как это исправить. Учтите, что ваш код очень длинный, люди будут игнорировать ваш вопрос, как только увидят так много кода и вообще никаких подсказок... просто совет, чтобы быстрее получить ответ! 08.03.2012
  • ... или добавьте точку останова исключения и посмотрите точную строку, в которой возникла проблема. Навигатор точек останова, знак плюс внизу слева, добавить точку останова исключения. 08.03.2012
  • Спасибо Shubhank, tonio и jrturton за ваши ответы... я вставил четыре точки останова, и в первом окне @synthesize показано, что поток остановлен на точке останова 8; 08.03.2012
  • @Shubhank: код не достигает [рецептов addObject:recipe]; , до этого вызывается только поток SIGABRT... 08.03.2012
  • добавьте точки останова к каждой функции.. когда она выйдет из строя.. обратите внимание на последнюю точку останова функции, которую она остановила.. затем обновите свой код... чтобы указать только эту функцию.. мы найдем ошибку. 08.03.2012
  • я добавил точку останова NSArray * viewControllers = [self segmentViewControllers]; и программа остановилась в self.segmentedControl = [[UISegmentedControl alloc] initWithItems:[viewControllers arrayByPerformingSelector:@selector(selectedIndex)]]; 08.03.2012
  • Вы можете заменить [viewControllers arrayByPerformingSelector:@selector(title)] на [viewControllers valueForKeyPath:@"@unionOfObjects.title"], чтобы избежать зависимости от внешнего кода. См. ответ здесь: stackoverflow.com/a/16569259/296446 15.05.2013

Ответы:


1

На самом деле вы не выделяете память массиву, поэтому вы получаете NSInvalidArgumentException

Попробуй это

NSArray * viewControllers = [NSArray arrayWithArray:[self segmentViewControllers]];
09.03.2012
  • я попробовал приведенный выше код вместо NSArray * viewControllers = [self segmentViewControllers]; все та же ошибка :( 09.03.2012
  • Новые материалы

    Кластеризация: более глубокий взгляд
    Кластеризация — это метод обучения без учителя, в котором мы пытаемся найти группы в наборе данных на основе некоторых известных или неизвестных свойств, которые могут существовать. Независимо от..

    Как написать эффективное резюме
    Предложения по дизайну и макету, чтобы представить себя профессионально Вам не позвонили на собеседование после того, как вы несколько раз подали заявку на работу своей мечты? У вас может..

    Частный метод Python: улучшение инкапсуляции и безопасности
    Введение Python — универсальный и мощный язык программирования, известный своей простотой и удобством использования. Одной из ключевых особенностей, отличающих Python от других языков, является..

    Как я автоматизирую тестирование с помощью Jest
    Шутка для победы, когда дело касается автоматизации тестирования Одной очень важной частью разработки программного обеспечения является автоматизация тестирования, поскольку она создает..

    Работа с векторными символическими архитектурами, часть 4 (искусственный интеллект)
    Hyperseed: неконтролируемое обучение с векторными символическими архитектурами (arXiv) Автор: Евгений Осипов , Сачин Кахавала , Диланта Хапутантри , Тимал Кемпития , Дасвин Де Сильва ,..

    Понимание расстояния Вассерштейна: мощная метрика в машинном обучении
    В обширной области машинного обучения часто возникает необходимость сравнивать и измерять различия между распределениями вероятностей. Традиционные метрики расстояния, такие как евклидово..

    Обеспечение масштабируемости LLM: облачный анализ с помощью AWS Fargate и Copilot
    В динамичной области искусственного интеллекта все большее распространение получают модели больших языков (LLM). Они жизненно важны для различных приложений, таких как интеллектуальные..