gpt4 book ai didi

iphone - NSUserDefaults 未写入磁盘

转载 作者:行者123 更新时间:2023-12-03 16:23:14 24 4
gpt4 key购买 nike

我为 NSUserDefaults 设置了一些值,如果我在不退出应用程序的情况下检索它们,则一切正常。当我重新启动应用程序时,95% 的情况下更改都会消失。在 5% 的时间内一切都可以正常保存。

我第一次遇到这个问题。在我的其他应用程序中,我通常不会将 NSString 保存在 NSUserDefaults 中。保存 NSString 可能会导致问题吗?

这是我的代码:

    -(void) mayShowFeedbackMessage
{
NSDateFormatter *dateFormatter = [ [NSDateFormatter alloc] init];
[dateFormatter setTimeStyle: NSDateFormatterLongStyle];
[dateFormatter setDateStyle: NSDateFormatterMediumStyle];

if ([ [NSUserDefaults standardUserDefaults] objectForKey: @"ratingsMessage_shown_on_date"])
{
NSString *lastRatingDateString = [ [NSUserDefaults standardUserDefaults]
objectForKey: @"ratingsMessage_shown_on_date"];
NSDate *lastRatingDate = [dateFormatter dateFromString: lastRatingDateString];

DebugLog(@"lastRatingDateString: %@", lastRatingDateString);
DebugLog(@"time since last message: %.0f", [ [NSDate date] timeIntervalSinceDate: lastRatingDate]);

if ( [ [NSDate date] timeIntervalSinceDate: lastRatingDate] >= 120.0f )
{
[self showFeedbackMessage];

NSDateFormatter *dateFormatter = [ [NSDateFormatter alloc] init];
[dateFormatter setTimeStyle: NSDateFormatterLongStyle];
[dateFormatter setDateStyle: NSDateFormatterMediumStyle];

NSString *dateString = [dateFormatter stringFromDate: [NSDate date] ];
[dateFormatter release];

[ [NSUserDefaults standardUserDefaults] setObject: dateString
forKey: @"ratingsMessage_shown_on_date" ];

lastRatingDateString = [ [NSUserDefaults standardUserDefaults]
objectForKey: @"ratingsMessage_shown_on_date"];
DebugLog(@"new date: %@", lastRatingDateString);

}
}
else
{
NSDateFormatter *dateFormatter = [ [NSDateFormatter alloc] init];
[dateFormatter setTimeStyle: NSDateFormatterLongStyle];
[dateFormatter setDateStyle: NSDateFormatterMediumStyle];

NSString *dateString = [dateFormatter stringFromDate: [NSDate date] ];
[dateFormatter release];

[ [NSUserDefaults standardUserDefaults] setObject: dateString
forKey: @"ratingsMessage_shown_on_date" ];

NSString *lastRatingDateString = [ [NSUserDefaults standardUserDefaults]
objectForKey: @"ratingsMessage_shown_on_date"];
DebugLog(@"new date: %@", lastRatingDateString);

}

[dateFormatter release];
}

谢谢。

最佳答案

进行必要的更改后添加以下代码解决了该问题:

[ [NSUserDefaults standardUserDefaults] synchronize];

关于iphone - NSUserDefaults 未写入磁盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1725852/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com