ios专题

本地缓存

2016-08-12  本文已影响8人  HeavenWong
#import <Foundation/Foundation.h>
@interface Core : NSObject
//缓存搜索的数组
+(void)SearchText :(NSString *)seaTxt;
//清除缓存数组
+(void)removeAllArray;
@end
#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);
    
}

上一篇下一篇

猜你喜欢

热点阅读