iOS 利用UserDefaults快速实现常用搜索页记录工具

1.需求分析

一般搜索页的历史记录需求

  1. 存储内容为字符串
  2. 存储内容要去重
  3. 存储个数会有个上限
  4. 存储个数达到上限后要先前挤掉旧数据,保留新数据
  5. 调用动作一般为 存 / 读 / 清空全部

2.实现

.h文件

//  RPCustomTool.h
//  RollingPin
//
//  Created by RollingPin on 2020/12/31.
//  Copyright © 2020 RollingPin. All rights reserved.
//
#import 
#import 
@interface RPCustomTool : NSObject
/// 存
+ (void)saveHistoryString:(NSString *)saveStr;
/// 读
+ (NSArray *)readHistoryList;
/// 清空
+ (void)deleteHistoryList;
@end

.m文件

//  RPCustomTool.h
//  RollingPin
//
//  Created by RollingPin on 2020/12/31.
//  Copyright © 2020 RollingPin. All rights reserved.
//
#import "RPCustomTool.h"
@implementation RPCustomTool

#pragma mark - 存
+ (void)saveHistoryString:(NSString *)saveStr
{
     
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSArray *savedArray = [userDefaults arrayForKey:@"RPSearchHistoryMark"];
    NSMutableArray *savedMuArray = [[NSMutableArray alloc]initWithArray:savedArray];
    //去重
    NSString *repetitiveStr = @"";
    for (NSString * oneStr in savedArray) {
     
        if ([oneStr isEqualToString:saveStr]) {
     
            repetitiveStr = oneStr;
            break;
        }
    }
    if (repetitiveStr.length >0) {
     
        [savedMuArray removeObject:repetitiveStr];
    }
    [savedMuArray addObject:saveStr];
    //设置最大保存数
    if(savedMuArray.count > 10)
    {
     
        [savedMuArray removeObjectAtIndex:0];
    }
    //最后再存储到NSUserDefaults中
    [userDefaults setObject:savedMuArray forKey:@"RPSearchHistoryMark"];
    [userDefaults synchronize];
}
#pragma mark - 读
+ (NSArray *)readHistoryList
{
     
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    //读取数组NSArray类型的数据
    NSArray *savedArray = [userDefaults arrayForKey:@"RPSearchHistoryMark"];
    NSLog(@"savedArray======%@",savedArray);
    return [savedArray copy];
}
#pragma mark - 清空
+ (void)deleteHistoryList
{
     
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:[NSArray array] forKey:@"RPSearchHistoryMark"];
    [userDefaults synchronize];
}
@end

你可能感兴趣的:(iOS,搜索历史,nsuserDefaults,保存历史记录,存储)