OSX NSUserDefaults not Working

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-06 04:18:30

问题


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


回答1:


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
    


来源:https://stackoverflow.com/questions/28881622/osx-nsuserdefaults-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!