.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