美文网首页iOS开发拾碎
iOS 利用UserDefaults快速实现常用搜索页记录工具

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

作者: 王加水 | 来源:发表于2020-12-09 17:47 被阅读0次

    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 <Foundation/Foundation.h>
    #import <UIKit/UIKit.h>
    @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 利用UserDefaults快速实现常用搜索页记录工具

        本文链接:https://www.haomeiwen.com/subject/fvahgktx.html