Search code examples
iosnsuserdefaultsios8ios-app-extensionios-app-group

NSUserDefault can't save & load in Extension in iOS8


I need to save data to NSUserDefault in my iOS Custom Keyboard. I have successfully created App Groups and entitlement in developer portal and XCode.

Here is how i save my value with UISwitch

- (IBAction)switchAction:(id)sender
{
    [self.defaults setBool:self.myKey.on forKey:@"myValue"];

    [self.defaults synchronize];
}

and here is how i load value in KeyboardView.

self.defaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.mycompany.customkeyboard"];

if([self.defaults boolForKey:@"myValue"])
{
    self.backgroundColor = [UIColor redColor];
}

else
{
    self.backgroundColor = [UIColor blackColor];
}

It's doesn't work and doesn't load value.

How can i save and load data?


Solution

  • Initialize your NSUserDefaults object like this in all applications in the app group and they will share the database:

    [[NSUserDefaults alloc] initWithSuiteName:@"group identifier"];
    

    Keep in mind everything from the [NSUserDefaults standardUserDefaults] database for each application will not carry over into this database.

    The documentation indicates that [NSUserDefaults standardUserDefaults] should return the shared database like the above code does, however it does not. I filed this as a bug (rdar://17164758).

    And don't forget to synchronize the database:

    [yourDefaults synchronize];