gpt4 book ai didi

ios - NSUserDefaults 在使用应用程序时保存并重新加载,但在应用程序重新启动时重置

转载 作者:行者123 更新时间:2023-12-01 18:54:02 26 4
gpt4 key购买 nike

如果这是用户在特定日期第一次收到消息,我有一种方法可以增加计数器。下面的代码:

//here we decide if to increment it or not
-(BOOL)canIncrementCountForUser: (NSString *)user {

//erase the dictionary if it's a new day
[self flushDictionaryIfNeeded];

//load up a dictionary
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *dictionary = [defaults objectForKey:@"uniqueSentToday"];

NSLog(@"%@", [dictionary allKeys]);

//if empty it's a yes
if([dictionary count]==0){
NSLog(@"empty dictionary");
NSLog(@"First message for %@ today!",user);
NSDate *now = [NSDate date];
[dictionary setObject:now forKey:user]; //do I need to set it back again?
[defaults synchronize];
return YES;

}

//if it's not empty it's only a yes if the key doesn't exist
else {

//not in dict so unique
if(![dictionary objectForKey:user]){
NSLog(@"First message for %@ today!",user);
NSDate *now = [NSDate date];
[dictionary setObject:now forKey:user]; //do I need to set it back again?
[defaults synchronize];
return YES;

}


else {

NSLog(@"Already messaged %@ today!",user);
return NO;



}




}


}

-(void)flushDictionaryIfNeeded{

//set dictionary
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *dictionary = [defaults objectForKey:@"uniqueSentToday"];

if([dictionary count]>0) {

//get any date
NSDate *aDate = nil;
NSArray *values = [dictionary allValues];
aDate = [values objectAtIndex:0];

NSDateComponents *otherDay = [[NSCalendar currentCalendar] components:NSCalendarUnitEra|NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:aDate];
NSDateComponents *today = [[NSCalendar currentCalendar] components:NSCalendarUnitEra|NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:[NSDate date]];
if([today day] == [otherDay day] &&
[today month] == [otherDay month] &&
[today year] == [otherDay year] &&
[today era] == [otherDay era]) {

NSLog(@"Don't flush");
}

else {

NSLog(@"It's a new day! erase dictionary!");
[dictionary removeAllObjects];
[defaults synchronize];

}

}

}

如果向用户发送消息,则将使用用户的用户名作为键创建 NSDate 对象。如果键不存在,则可以递增计数器并添加键,如果确实存在,则该方法返回 false。如果是新的一天,我还有一种方法可以删除所有内容。代码一切正常,似乎在使用程序时 NSMutableDictionary 正在保存到应用程序中,但是当我重新启动应用程序时,字典将为空。有人可以告诉我为什么会发生这种情况吗?谢谢

最佳答案

您修改了 dictionary但从不退缩defaults ... 你需要:

[defaults setObject:dictionary forKey:@"uniqueSentToday"];

保存默认值。

关于ios - NSUserDefaults 在使用应用程序时保存并重新加载,但在应用程序重新启动时重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28938046/

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