Oiproks
Oiproks

Reputation: 794

EXC_BAD_ACCESS at the end of a method

In this method I add the content of UITextFields, images and other strings in a sqlite database. Everything works fine. I mean, when i press the "Add" button, the "OK" image appear, the sound play and all the contents are added to the database (I can check restarting the application). But after all of this, I have this error in the "main.m"

This is the method:

-(IBAction)addItem:(id)sender { //gestione pulsante aggiunta elemento
    if (([itemNameField.text length] == 0) || ([priceField.text length] == 0) || ([priceField.text doubleValue] == 0.0) || ((incomeOutcome.selectedSegmentIndex != 0) && (incomeOutcome.selectedSegmentIndex != 1))) {
        if ([itemNameField.text length] == 0) {
        statusLabel.text = [[NSString alloc] initWithFormat: @"Specificare un nome."];
        } else if (([priceField.text length] == 0) || ([priceField.text doubleValue] == 0.0)) {
            statusLabel.text = [[NSString alloc] initWithFormat: @"Specificare un prezzo."];
        } else if ((incomeOutcome.selectedSegmentIndex != 0) && (incomeOutcome.selectedSegmentIndex != 1)) {
            statusLabel.text = [[NSString alloc] initWithFormat: @"Specificare \"Income/Outcome\" ."];            
        }
        if (!categoriaLabel.hidden) {
            [self hideThemAll];
        }
        [incomeOutcome setSelectedSegmentIndex:-1];
        statusLabel.hidden = NO;
        error = true;
        [self playSound];
        [ok setImage:[UIImage imageNamed:@"error.png"]];
        ok.hidden = NO;
        return;
    }
    //apriamo il database
    sqlite3 *db;
    int dbrc; //Codice di ritorno del database (database return code)
    iWalletAppDelegate *appDelegate = (iWalletAppDelegate*) [UIApplication sharedApplication].delegate;
    const char *dbFilePathUTF8 = [appDelegate.dbFilePath UTF8String];
    dbrc = sqlite3_open(dbFilePathUTF8, &db);
    if (dbrc) {
        NSLog(@"Impossibile aprire il Database!");
        return;
    }
    //database aperto! Inseriamo valori nel database.
    sqlite3_stmt *dbps; //Istruzione di preparazione del database
    NSString *insertStatementsNS;
    if (incomeOutcome.selectedSegmentIndex == 0) {
        insertStatementsNS = [NSString stringWithFormat: @"insert into \"shoppinglist\" (item, price, groupid, incout, path,  dateadded) values (\"%@\", \"%@\", \"Entrata\", %d, \"%@\", DATETIME('NOW'))", itemNameField.text, priceField.text, incomeOutcome.selectedSegmentIndex, imagePath];
    } else if ([categoryNameField.text length] != 0) { 
        insertStatementsNS = [NSString stringWithFormat: @"insert into \"shoppinglist\" (item, price, groupid, incout, path, dateadded) values (\"%@\", \"%@\", \"%@\", %d, \"%@\", DATETIME('NOW'))", itemNameField.text, priceField.text, categoryNameField.text, incomeOutcome.selectedSegmentIndex, imagePath]; 
    } else { 
        insertStatementsNS = [NSString stringWithFormat: @"insert into \"shoppinglist\" (item, price, groupid, incout, path, dateadded) values (\"%@\", \"%@\", \"Varie\", %d, \"%@\", DATETIME('NOW'))", itemNameField.text, priceField.text, incomeOutcome.selectedSegmentIndex, imagePath];
    }
    const char *insertStatement = [insertStatementsNS UTF8String];
    dbrc = sqlite3_prepare_v2(db, insertStatement, -1, &dbps, NULL);
    dbrc = sqlite3_step(dbps);

    //faccio pulizia rilasciando i database
    sqlite3_finalize(dbps);
    sqlite3_close(db);

    // Pulisci i campi e indica successo nello status
    statusLabel.hidden = NO;
    statusLabel.text = [[NSString alloc] initWithFormat: @"Aggiunto %@", itemNameField.text];

    itemNameField.text = @"";
    priceField.text = @"";
    categoryNameField.text = @"";
    imagePath = @"";
    [incomeOutcome setSelectedSegmentIndex:-1];
    error = false;
    [self hideThemAll];
    [self playSound];
    [ok setImage:[UIImage imageNamed:@"ok.png"]];
    ok.hidden = NO;
    nome = @"";
    prezzo =@"";
    [photoPreview setImage:[UIImage imageNamed:@"noPhoto.png"]];
    [[self parentViewController]dismissModalViewControllerAnimated:YES];
}    

EDIT

Thanks to Isaac I (maybe) found the issue: I wasn't retaining the picture I took from the camera.

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissModalViewControllerAnimated:YES];
    int r = arc4random() % 9999;
    NSDate *date = [NSDate date];
    NSString *photoName = [dateNameFormatter stringFromDate:date];
    photoName = [photoName stringByAppendingString:[NSString stringWithFormat:@"%d", r]];

    if (imagePath) {
        [imagePath release];
    }
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    imagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", photoName]];
    [imagePath retain];

    UIImage *picture = [info objectForKey:UIImagePickerControllerOriginalImage];

    // ----- CODE FOR SCALE THE IMAGE ----- //
    if (picture.size.width == 1936) {
        picture = [picture scaleToSize:CGSizeMake(480.0f, 720.0f)];
    } else {
        picture = [picture scaleToSize:CGSizeMake(720.0f, 480.0f)];
    }

    photoPreview.image =  picture;

    photoPreview.contentMode = UIViewContentModeScaleAspectFit;

    CGRect frame = photoPreview.frame;
    if (picture.size.width == 480) {
        frame.size.width = 111.3;
        frame.size.height =167;
    } else {
        frame.size.width = 167;
        frame.size.height =111.3;
    }
    photoPreview.frame = frame;
    // ----- ----- - END CODE - ----- ----- //    

    NSData *webData = UIImagePNGRepresentation(picture);
    CGImageRelease([picture CGImage]);
    [webData writeToFile:imagePath atomically:YES];
    [picture retain]; // <-- This little thing here!
    //imgPicker = nil;
}

Now it works! But if you can see other problems, please let me notice them.

Upvotes: 1

Views: 1061

Answers (3)

beryllium
beryllium

Reputation: 29767

There is no reason to create NSString like this:

 statusLabel.text = [[NSString alloc] initWithFormat: @"Specificare un nome."];

Simply write

statusLabel.text = @"Specificare un nome.";

Maybe it's not a cause of EXC_BAD_ACCESS, but at least you can avoid several memory leaks.

Upvotes: 4

makaron
makaron

Reputation: 1615

In my opinion isaac is right. I just want to add one guess. Most likely the error occurs when you invoke

[[self parentViewController]dismissModalViewControllerAnimated:YES];

By this moment, I think, something in you parentViewController is already released, so when you try to show it back, program turns to released variable and gives you a crash.

You can quite easily detect it just with the help of breakpoints.

Upvotes: 0

isaac
isaac

Reputation: 4897

Typically an EXC_BAD_ACCESS occurs when you are trying to access memory that has been deallocated. In your code sample, I don't see any [object release] calls (that's another problem entirely, unless you happen to be using ARC). But my guess it that this error is the result of a call that is being made outside of the scope of this method - something is being released prematurely.

You could paste your entire class, or, consider using the Instruments tool 'Zombies' to identify the dangling pointer which is (probably) causing this.

Upvotes: 3

Related Questions