我正在运行以下代码来保存发送的总字节数:
NSUInteger bytes = 10;
int newBytes = bytes+[[NSUserDefaults standardUserDefaults] integerForKey:@"TotalBytes"];
NSLog(@"newBytes %i", newBytes);
[[NSUserDefaults standardUserDefaults] setInteger:newBytes forKey:@"TotalBytes"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(@"%i", [[NSUserDefaults standardUserDefaults] integerForKey:@"TotalBytes"]);
数学似乎工作正常,newBytes 记录出正确的数字,然后当我运行同步命令时,NSLog 再次返回正确的值。但是,当此代码第二次运行时,键值仍设置为之前的值,并且未保存。
我在这里做了一些非常愚蠢的事情吗?帮忙!!?!
最佳答案
@mootymoots:您的代码确实没有任何问题,我在模拟器和 iTouch 中都尝试过,它写入并读取新的 +10 值...我还尝试直接在 iTouch 上启动我的应用程序(而不是通过 xCode)当我通过 xCode 再次运行时,该值是 +10 * nTimes 我使用该应用程序...
那么...您确定您正在使用此代码编写 standardUserDefaults 吗?
在 xcode 中尝试“menu:edit:find:find in project”并搜索 standardUserDefaults...
您也可以尝试“菜单:构建:清理所有目标”...
关于iphone - 对 NSUserDefaults 进行数学运算并重新保存 - 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5183507/