我应该如何以及在何处在实用程序应用程序中设置和加载NSUserDefaults?

时间:2010-04-17 07:05:58

标签: iphone nsuserdefaults

我已经在一些论坛上提供了几本书中的指示和建议,但是当我尝试设置用户首选项时,我的应用程序崩溃了。我在flipscreenViewController中的“done”方法中有以下几行:


    - (IBAction)done 
   {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setBool:musicOnOff.on forKey:kMusicPreference];
    [userDefaults setObject:trackSelection forKey:kTrackPreference];
    [self.delegate flipsideViewControllerDidFinish:self];   
   }

我的mainViewController中有以下方法:


    -(void)initialDefaults
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setBool:YES forKey:kMusicPreference];
    [userDefaults setObject:@"Infinity" forKey:kTrackPreference];
}

-(void) setvaluesFromPreferences
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];   
    BOOL musicSelection = [userDefaults boolForKey:kMusicPreference];
    NSString *trackSelection = [userDefaults objectForKey:kTrackPreference];
    if(musicSelection == YES)
    {
        if([trackSelection isEqualToString:@"Infinity"])
        song = [[BGMusic alloc]initWithPath:
                       [[NSBundle mainBundle] pathForResource:
                       @"Infinity" ofType:@"m4a"]];
        else if([trackSelection isEqualToString:@"Energy"])
        song = [[BGMusic alloc]initWithPath:
                       [[NSBundle mainBundle] pathForResource:
                       @"Energy" ofType:@"m4a"]];       
        else if([trackSelection isEqualToString: @"Enforcer"])
        song = [[BGMusic alloc]initWithPath:
                       [[NSBundle mainBundle] pathForResource:
                       @"Enforcer" ofType:@"m4a"]];     
        else if([trackSelection isEqualToString: @"Continuum"])     
        song = [[BGMusic alloc]initWithPath:
                       [[NSBundle mainBundle] pathForResource:
                       @"Continuum" ofType:@"m4a"]];        
        else if([trackSelection isEqualToString: @"Pursuit"])
        song = [[BGMusic alloc]initWithPath:
                       [[NSBundle mainBundle] pathForResource:
                       @"Pursuit" ofType:@"m4a"]];

        [song setRepeat:YES];
        counter = 0;
        }
        else 
        [song close];
    }

如果那里有人可以帮我看看我做错了什么,我将不胜感激。

1 个答案:

答案 0 :(得分:1)

在应用程序的上下文中,只要有意义,就应该保存首选项。如果您的代码崩溃,那么您需要熟悉调试器并找出原因。如果您需要帮助,那么您至少需要提供堆栈爬网。