0

Previously my NSUserDefaults working just fine but lately after upgraded to iOS 8, it fails in my simulator (not sure about real device as I do not have iOS 8 on real device). I have tested on iOS7 and it is working on both simulator and real device. So I am not sure is it iOS 8 problem or only iOS 8 simulator problem.

My problem is that it always return empty string even after I saved it.

My code as below:

+(void)SetStringValueForConfigurationKey: (NSString *) _objectkey withValue:(NSString *)_value
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults synchronize]; //let's make sure the object is synchronized
    [defaults setValue:_value forKey:_objectkey];
    [defaults synchronize];//make sure you're synchronized again
}

+(NSString *)GetStringValueForConfigurationKey: (NSString *)_objectkey
{
    //create an instance of NSUserDefaults
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults synchronize]; //let's make sure the object is synchronized
    if ([defaults stringForKey:_objectkey] == nil )
    {
        //I don't want a (null) returned
        return @"";
    }
    else
    {

        return [defaults stringForKey:_objectkey];
    }
}

Is there any way where I can upgrade the simulator to iOS 8.0.2? Or how can I find the cause of the problem?

Thanks.

Darshan Kunjadiya
  • 3,323
  • 1
  • 29
  • 31
TPG
  • 2,811
  • 1
  • 31
  • 52

2 Answers2

2

you try to set

[defaults setValue:_value forKey:_objectkey];

But you take later

return [defaults stringForKey:_objectkey];

Please try with

[defaults setObject:<#(id)#> forKey:<#(NSString *)#>];
[defaults objectForKey:<#(NSString *)#>];
Matz
  • 1,006
  • 10
  • 27
0

I have discovered the root cause, there is different behaviour between iOS 7 and iOS 8.

To be in more details, I am facing this problem in my login screen. At the login screen itself, I have a selection that needed user to select in which I put in another View Controller via "Partial Curl" transition. Problem happens at this transition.

The problem is within this code below:

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];

}

In iOS 7, this function only called once during first load. But in iOS 8, it is being called again when transit back from "Partial Curl" VC back to the original login VC.

This is where the problem arose. I was resetting all my NSUserDefaults value within this function, therefore in iOS 8, whenever I stored and transit back to login VC, all the values are gone. Thus returning empty value. I fix my problem by changing my logic in this function to cater for the multiple call in iOS 8.

TPG
  • 2,811
  • 1
  • 31
  • 52