本地缓存

  • 可用于搜索历史记录缓存

  • .h文件

#import 
@interface Core : NSObject
//缓存搜索的数组
+(void)SearchText :(NSString *)seaTxt;
//清除缓存数组
+(void)removeAllArray;
@end
  • .m文件
#import "Core.h"
@implementation Core
//缓存搜索数组
+(void)SearchText :(NSString *)seaTxt
{
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    //读取数组NSArray类型的数据
    NSArray *myArray = [userDefaultes arrayForKey:@"myArray"];
    if (myArray.count > 0) {//先取出数组,判断是否有值,有值继续添加,无值创建数组
        
    }else{
        myArray = [NSArray array];
    }
    // NSArray --> NSMutableArray
    NSMutableArray *searTXT = [myArray mutableCopy];
    [searTXT addObject:seaTxt];
    if(searTXT.count > 30)
    {
        [searTXT removeObjectAtIndex:0];
    }
    //将上述数据全部存储到NSUserDefaults中
    //        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaultes setObject:searTXT forKey:@"myArray"];
    [userDefaultes synchronize];
}
// 清除搜索缓存
+(void)removeAllArray{
    NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults removeObjectForKey:@"myArray"];
    [userDefaults synchronize];
}

@end
  • 使用

// 清除缓存
[Core removeAllArray];
// 缓存
        [Core SearchText:textField.text];

// 取出缓存
        [self readNSUserDefaults];

  • 取出缓存
- (void)readNSUserDefaults {
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    NSArray *array = [userDefaultes arrayForKey:@"myArray"];
    self.searchDataArray = [NSMutableArray arrayWithArray:array];
    [self.tableView reloadData];
//    DLog(@"array搜索记录%@", array);
//    DLog(@"%@", self.searchDataArray);
//    DLog(@"%@", self.searchView.searchDataArray);
    
}

你可能感兴趣的:(本地缓存)