简体   繁体   中英

“EXEC_BAD_ACCESS” error when reading NSUserDefaults

I'm having an error occur when I read the NSUserDefaults (via InAppSettingsKit). I'm not sure if it's my code that's the issue though. I have set up an observer to check if there are any changes to the NSUserDefaults:

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self
           selector:@selector(setOptions)  
               name:NSUserDefaultsDidChangeNotification
             object:nil];

The method this calls is used to update the 'map type' of an MKMapView:

- (void)setOptions
{
    // Get the map style
    NSString *mapStyle = [[NSUserDefaults standardUserDefaults] stringForKey:kMapType];

    // Update map style
    if ([mapStyle isEqualToString:@"Hybrid"]) 
    {
        map.mapType = MKMapTypeHybrid;
    }
    else if ([mapStyle isEqualToString:@"Map"]) 
    {
        map.mapType = MKMapTypeStandard;
    }
    else if ([mapStyle isEqualToString:@"Satellite"]) 
    {
        map.mapType = MKMapTypeSatellite;
    }

    [mapStyle release];
}

The app is set up such that you press a button and the InAppSettingsKit is initialised, within this I change the setting for the map type to be displayed and go back to the main screen in my app. At this point the map seems to update correctly and there are no issues. The issue occurs when I try to re-launch the InAppSettingsKit to change the map type again.

Does anyone know if it's my code that's the issue, if so how can I go about fixing it?

just remove the code-line: [mapStyle release]

the stringForKey: will return an autoreleased NSString . So your code is not responsible for releasing. It works fine in the first iteration because the first release call will dealloc that string but the NSUserDefaults still has a pointer to that String but is not used. In the second iteration you get that pointer and try to call isEqualToString on that dealloc-ed object wich will cause the BAD_ACCESS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM