diff --git a/keyBoard/Class/Search/VC/KBSearchVC.m b/keyBoard/Class/Search/VC/KBSearchVC.m index 223198d..c015bec 100644 --- a/keyBoard/Class/Search/VC/KBSearchVC.m +++ b/keyBoard/Class/Search/VC/KBSearchVC.m @@ -22,6 +22,7 @@ static NSString * const kSkinCellId = @"KBSkinCardCell"; static NSString * const kHeaderId = @"KBSearchSectionHeader"; static NSString * const kMoreCellId = @"KBHistoryMoreCell"; static NSString * const kMoreToken = @"__KB_MORE__"; // 用于内部计算的占位标识 +static NSString * const kKBSearchHistoryDefaultsKey = @"KBSearchHistoryWords"; typedef NS_ENUM(NSInteger, KBSearchSection) { KBSearchSectionHistory = 0, @@ -85,13 +86,11 @@ typedef NS_ENUM(NSInteger, KBSearchSection) { make.left.right.bottom.equalTo(self.view); }]; - // 初始化测试数据 - self.historyWords = [@[KBLocalized(@"果冻橙"), - KBLocalized(@"芒果"), - KBLocalized(@"有机水果卷心菜"), - KBLocalized(@"水果萝卜"), - KBLocalized(@"熟冻帝王蟹"), - KBLocalized(@"赣南脐橙")] mutableCopy]; + // 从本地读取历史搜索 + self.historyWords = [[self loadHistoryWordsFromLocal] mutableCopy]; + if (!self.historyWords) { + self.historyWords = [NSMutableArray array]; + } self.recommendedThemes = @[]; [self.collectionView reloadData]; @@ -125,6 +124,7 @@ typedef NS_ENUM(NSInteger, KBSearchSection) { } // 插入最前 [self.historyWords insertObject:trim atIndex:0]; + [self saveHistoryWordsToLocal:self.historyWords]; [self.collectionView reloadData]; } @@ -235,9 +235,28 @@ typedef NS_ENUM(NSInteger, KBSearchSection) { /// 清空历史 - (void)clearHistory { [self.historyWords removeAllObjects]; + self.historyExpanded = NO; + [self saveHistoryWordsToLocal:self.historyWords]; [self.collectionView reloadData]; } +- (NSArray *)loadHistoryWordsFromLocal { + id obj = [[NSUserDefaults standardUserDefaults] objectForKey:kKBSearchHistoryDefaultsKey]; + if (![obj isKindOfClass:NSArray.class]) { return @[]; } + NSMutableArray *result = [NSMutableArray array]; + for (id item in (NSArray *)obj) { + if ([item isKindOfClass:NSString.class] && ((NSString *)item).length > 0) { + [result addObject:item]; + } + } + return result.copy; +} + +- (void)saveHistoryWordsToLocal:(NSArray *)words { + NSArray *safe = [words isKindOfClass:NSArray.class] ? words : @[]; + [[NSUserDefaults standardUserDefaults] setObject:safe forKey:kKBSearchHistoryDefaultsKey]; +} + #pragma mark - UICollectionViewDataSource - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {