如果是第一次在特定日期向用户发送消息,我有一种增加计数器的方法。代码如下:
//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在使用程序时正在保存到应用程序中,但是当我重新启动应用程序时,字典将为空。有人能指点我为什么会这样吗?感谢
答案 0 :(得分:2)
您修改了dictionary
但从未撤回defaults
...您需要:
[defaults setObject:dictionary forKey:@"uniqueSentToday"];
保存默认值。
答案 1 :(得分:1)
您需要将字典存回用户默认值,因为您收到的字典是不可变的。虽然您将其设置为可变,但更改不会反映在用户默认的原始存储字典中。