-(void)SearchText :(NSString *)seaTxt { _SearchText = [NSMutableArray arrayWithObjects:seaTxt, nil]; NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; [userDefaults setObject:_SearchText forKey:@"myArray"]; NSLog(@"__SearchText1111===%@",_SearchText); } -(void)readNSUserDefaults { NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults]; NSArray *myArray = [userDefaultes arrayForKey:@"myArray"]; NSLog(@"myArray======%@",myArray); //_oneSearchBar.text = [myArray objectAtIndex:0]; }
上面是我的代码,每点一次搜索按钮调一次SearchText方法,然后在下次viewDidLoad的时候调用readNSUserDefaults方法,问题是从NSUserDefaults中读出来的数据只有一条,诸位,如果我要保存多条数据该如何改
-(void)SearchText :(NSString *)seaTxt { NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults]; //读取数组NSArray类型的数据 NSArray *myArray = [userDefaultes arrayForKey:@"myArray"]; // NSArray --> NSMutableArray NSMutableArray *searTXT = [myArray mutableCopy]; [searTXT addObject:seaTxt]; if(searTXT.count > 5) { [searTXT removeObjectAtIndex:0]; } //将上述数据全部存储到NSUserDefaults中 NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; [userDefaults setObject:searTXT forKey:@"myArray"]; } -(void)readNSUserDefaults { NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults]; //读取数组NSArray类型的数据 NSArray *myArray = [userDefaultes arrayForKey:@"myArray"]; NSLog(@"myArray======%@",myArray); }
如果要保存的数据多的话,也可以保存成文本的形式。
|