Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OSX NSUserDefaults not Working

This code gives me always NO in my application. It does indeed work in any other project I copy it... so something must be messed up with my standardUserDefaults, but I absolutely don't know how this can happen and how to solve it!

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:YES forKey:@"myKey"];

BOOL test = [defaults boolForKey:@"myKey"];
// test is ALWAYS NO here!

Can anybody hint me, where to start or how to get rid of this?

It's a mixed project with swift and objective c and get the same behavior in me AppDelegate.swift, when I put this directly in my applicationDidFinishLaunching

let defaults = NSUserDefaults.standardUserDefaults()        
defaults.setBool(true, forKey: "myKey")

let test = defaults.boolForKey("myKey")
// test ALWAYS false here   

Before someone asks: - yes, even with synchronize called between it - yes this is the whole code, nothing between the lines... set and get it right after does not work

like image 819
Axel Zehden Avatar asked Feb 11 '23 18:02

Axel Zehden


1 Answers

I found a solution, how to fix it, but not why this happens and no clean, good way so far.

If anybody could explain this and give me a better solution, do so!

  1. the problem was: If you delete the container of a sandboxed app, you also delete the plist for the NSUserDefaults and it's not created again and so NSUserDefaults simply is not working.

  2. the workaround: As I found here https://ind.ie/labs/blog/app-sandbox-updating-nsuserdefaults-fails-after-deleting-apps-container-directory/ it's a problem with the permanent bookmark of the system. Well just to empty the trash does not work for me, but what worked: I simply created the missing file!

    touch ~/Library/Containers/com.example.myapp/Data/Library/Preferences/com.example.myapp.plist
    
like image 159
Axel Zehden Avatar answered Feb 13 '23 06:02

Axel Zehden