iOSはUserDefaultsを利用して、共通の検索ページ記録ツールを迅速に実現
9742 ワード
1.需要分析
一般検索ページの履歴要件
2.実現
.hファイル
// RPCustomTool.h
// RollingPin
//
// Created by RollingPin on 2020/12/31.
// Copyright © 2020 RollingPin. All rights reserved.
//
#import
#import
@interface RPCustomTool : NSObject
///
+ (void)saveHistoryString:(NSString *)saveStr;
///
+ (NSArray *)readHistoryList;
///
+ (void)deleteHistoryList;
@end
.mファイル
// RPCustomTool.h
// RollingPin
//
// Created by RollingPin on 2020/12/31.
// Copyright © 2020 RollingPin. All rights reserved.
//
#import "RPCustomTool.h"
@implementation RPCustomTool
#pragma mark -
+ (void)saveHistoryString:(NSString *)saveStr
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSArray *savedArray = [userDefaults arrayForKey:@"RPSearchHistoryMark"];
NSMutableArray *savedMuArray = [[NSMutableArray alloc]initWithArray:savedArray];
//
NSString *repetitiveStr = @"";
for (NSString * oneStr in savedArray) {
if ([oneStr isEqualToString:saveStr]) {
repetitiveStr = oneStr;
break;
}
}
if (repetitiveStr.length >0) {
[savedMuArray removeObject:repetitiveStr];
}
[savedMuArray addObject:saveStr];
//
if(savedMuArray.count > 10)
{
[savedMuArray removeObjectAtIndex:0];
}
// NSUserDefaults
[userDefaults setObject:savedMuArray forKey:@"RPSearchHistoryMark"];
[userDefaults synchronize];
}
#pragma mark -
+ (NSArray *)readHistoryList
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
// NSArray
NSArray *savedArray = [userDefaults arrayForKey:@"RPSearchHistoryMark"];
NSLog(@"savedArray======%@",savedArray);
return [savedArray copy];
}
#pragma mark -
+ (void)deleteHistoryList
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:[NSArray array] forKey:@"RPSearchHistoryMark"];
[userDefaults synchronize];
}
@end