开发者

How to make NSUserDefaults data last for 3 sessions

I have this piece of code

 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];  
        if (![defaults objectForKey:@"firstRuns"]){

            开发者_如何学C[defaults setObject:[NSDate date] forKey:@"firstRuns"];
            if ([cellValue isEqual: @"First"] || [cellValue isEqual: @"Primo"]){   
                cell.backgroundColor = [UIColor yellowColor];
            } else {
                cell.backgroundColor = [UIColor whiteColor];
            }
        }
        [[NSUserDefaults standardUserDefaults] synchronize];

in

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

in order that the background of the row called "Primo" or "First" is set to yellow for the first use of the user.

I want the yellow background to last at least 3 sessions, how can i do that? Thanks


Something like:

NSNumber *runNumber = [[NSUserDefaults standardUserDefaults] objectForKey:@"runNum"];
if (runNumber) {
    if ([runNumber intValue] < 3) {
        if ([cellValue isEqual:@"First"] || [cellValue isEqual:@"Primo"]) {
            cell.backgroundColor = [UIColor yellowColor];
        } else {
            cell.backgroundColor = [UIColor whiteColor];
        }
        [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:[runNumber intValue] + 1] forKey:@"runNum"];
    } else {
        cell.backgroundColor = [UIColor whiteColor];
    }
} else {
    [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:1] forKey:@"runNum"];
    cell.backgroundColor = [UIColor whiteColor];
}
[[NSUserDefaults standardUserDefaults] synchronize]; 


Use the UserDefaults in applicationDidLaunch:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];    
NSInteger sessionCount = [[defaults objectForKey:@"sessionCount"] intValue]; 

sessionCount++;

[defaults setInteger:sessionCount forKey:@"sessionCount"];

Use that value in your tableview session to trigger yellow or white

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜