美文网首页iOS开发者笔记
分享一个搜索历史工具类

分享一个搜索历史工具类

作者: 少少少少少少少 | 来源:发表于2017-02-08 17:04 被阅读76次
    WechatIMG1.jpeg

    .h文件

    #import <Foundation/Foundation.h>
    
    @interface YPSearchTool : NSObject
    
    @property (nonatomic, strong) NSMutableArray *SearchDataArray;
    /**
     *    添加搜索历史
     *    @param searchStr 新加的输入条目
     */
    + (void)addSearchRecord:(NSString *)searchStr;
    
    /**
     *    获取所有的搜索历史
     *    @return 搜索历史 字符数组
     */
    + (NSArray *)getAllSearchHistory;
    
    /**
     *    清空搜索历史
     */
    + (void)clearAllSearchHistory;
    
    @end
    

    .m文件

    #import "YPSearchTool.h"
    #define RecordCount 3      //存储数量
    #define SEARCH_HISTORY [[NSUserDefaults standardUserDefaults] arrayForKey:@"SearchHistory"]
    @implementation YPSearchTool
    + (void)addSearchRecord:(NSString *)searchStr
    {
        NSMutableArray *searchArray = [[NSMutableArray alloc]initWithArray:SEARCH_HISTORY];
        if (searchArray == nil) {
            searchArray = [[NSMutableArray alloc]init];
        } else if ([searchArray containsObject:searchStr]) {
            [searchArray removeObject:searchStr];
        } else if ([searchArray count] >= RecordCount) {
            [searchArray removeObjectsInRange:NSMakeRange(RecordCount - 1, [searchArray count] - RecordCount + 1)];
        }
        [searchArray insertObject:searchStr atIndex:0];
        [[NSUserDefaults standardUserDefaults] setObject:searchArray forKey:@"SearchHistory"];
    }
    
    + (NSArray *)getAllSearchHistory
    {
        return SEARCH_HISTORY;
    }
    
    + (void)clearAllSearchHistory
    {
        [[NSUserDefaults standardUserDefaults] setObject:[[NSMutableArray alloc]init] forKey:@"SearchHistory"];
    }
    @end
    

    相关文章

      网友评论

        本文标题:分享一个搜索历史工具类

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