NSUserDefaults errors in logs

2019-02-11 15:44发布

问题:

I get some error messages in logs

 [User Defaults] Failed to write value for key GameId in CFPrefsPlistSource<0x1740faf00> (Domain: xxx.xxxxxx, User: kCFPreferencesCurrentUser, ByHost: No, Container: (null)): Path not accessible, switching to read-only
[User Defaults] attempt to set <private> for key in <private> in read-only (due to a previous failed write) preferences domain CFPrefsPlistSource<0x1740faf00> (Domain: xxx.xxxxxx, User: kCFPreferencesCurrentUser, ByHost: No, Container: (null))

What does cause this?

That's how I use NSUserDefaults:

- (NSString *)gameId
{
    if (_gameId)
        return _gameId;

    _gameId = [[NSUserDefaults standardUserDefaults] objectForKey:@"GameId"];
    return _gameId;
}

- (void)setGameId:(NSString *)aGameId
{
    _gameId = aGameId;
    [[NSUserDefaults standardUserDefaults] setObject:_gameId forKey:@"GameId"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

回答1:

Lot of people are finding this issue on Xcode 8.

"As crazy as it sounds try rebooting phone and host, sometimes Xcode can get stuck for sum reason only restart helps.

build with Xcode 8.1 Beta and you will see the same warning, but you will also get the value. "

reference : https://forums.developer.apple.com/thread/51348



回答2:

I was getting a similar error:

[User Defaults] attempt to set <private> for key in <private> in read-only (due to a previous failed write) preferences domain CFPrefsPlistSource<0x1700f5f80>

but it only happened when I was plugged into Xcode.

A device reboot fixed this.



回答3:

if you suffer this problem when you try to save data to extension APP by using userDefault,maybe you had written this code : [[NSUserDefaults standardUserDefaults] initWithSuiteName:@"group.xxx.com"];,this code reset default userDefault. Actually,the correct code is : [[NSUserDefaults alloc] initWithSuiteName:@"group.xxx.com"]; http://www.jianshu.com/p/e782104c3bc3



回答4:

I just had the same error. The error for me was because I called synchronize multiple times.

By calling [userDefaults synchronize] just once all the error messages disappeared.



回答5:

I just deleted the app and installed again via Xcode. Using XCode 8.2.1.



回答6:

I'd like to share my solution for this problem. For my case, the error was a legitimate error and my data was not saved properly. It turns out the error was caused by having a NSUserDefaults "data saving" in a loop.

By "data saving" I mean this (pseudocode):

loop{
    [defaults setObject:@"Data" forKey:@"Key"];
    [defaults synchronize];
}

So the code executes this multiple times very fast and cause the problem. I guess "synchronize" cannot handle concurrent calls.

What needs to be done is:

loop{
    [defaults setObject:@"Data" forKey:@"Key"];
}
[defaults synchronize];

synchronize be called once after all the objects been set.