NSUserDefaults and sandboxing under Lion

2019-06-23 23:05发布

问题:

Moving one of my projects to support sandboxing as per Apple's requirements. I use UserDefaults like so:

[[NSUserDefaults standardUserDefaults] setObject:@(myNumber) forKey:myNumberKey];
[[NSUserDefaults standardUserDefaults] synchronize];

Everything works as expected until I enable sandboxing. If I have sandboxing enabled the app creates a lock file in it's sandbox directory ( .plist.lockfile) and doesn't create an actual .plist file.

What am I doing wrong and how do I store my settings in UserDefaults under sandbox environment?

Update: Installed fresh 10.7.3 with the latest Xcode on a separate Mac - the same project compiles and works fine with sandboxing enabled.

Also I've tried to run this project on my Mac where the sandbox doesn't work under different user account (freshly created) with exactly the same results - no go. At this point I think the problem is with system configuration on this particular mac. Question is though - is it safe to assume that I'm the only one with this weird problem? Probably not...

回答1:

That should work fine. If the preferences system is able to create the lock file, that means your app has appropriate privileges to create files in that directory and has correctly looked up the location where it should put them. Therefore, something else must be going wrong.

Is there any Console logging when this occurs? What's the return value of -synchronize?

(aside: in general -synchronize is not necessary and will just make your app slower, NSUserDefaults will handle that itself)