我有一个 uitableview,其中包含从应用程序本地的 JSON 文件填充的项目列表。一切都可以将列表放到表格中,并在选择(或取消选择)时将多个项目保存到 nsmutablearray 中。
问题是当用户离开视图并返回并选择另一个项目(或取消选择当前选择的项目)时。此时可变数组为空。
我不确定可变数组的 nsuserdefaults 保存是否是问题所在。它保存得很好,但是当视图重新出现(此时可变数组的值很好)并且用户触摸表格行时,数组再次为空。
我的 .h 文件:
@interface CategoriesViewController : UITableViewController {
NSMutableArray *_selectedItems;
NSString *filePath;
NSString *string;
}
// arForTable array will hold the JSON results from the api
@property (nonatomic, retain) NSArray *arForTable;
@property (nonatomic, retain) NSMutableArray *categorySelected;
@property (nonatomic, retain) NSString *jsonStringCategory;
@property(nonatomic, retain) UIView *accessoryView;
@end
我的 .m 文件:
@implementation CategoriesViewController
@synthesize arForTable = _arForTable;
- (void)viewDidLoad
{
[super viewDidLoad];
self.categorySelected = [[NSMutableArray alloc] init];
[self reloadMain];
// assignment reference so don't release
_selectedItems = [(AppDelegate *)[[UIApplication sharedApplication] delegate] selectedCategories];
self.tableView.hidden = NO;
}
-(void) reloadMain {
// countrySaved value from NSUserDefaults
NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
NSString *countryString = [defaults stringForKey:@"selectedCountryTableString"];
NSString *cityString = [defaults stringForKey:@"selectedCityTableString"];
NSLog(@"countrystring from category is %@", countryString);
NSLog(@"citystring from category is %@", cityString);
// getting path to the file
if ([defaults stringForKey:@"selectedCountryTableString"] == NULL) {
filePath = [[NSBundle mainBundle] pathForResource:@"categoriesit" ofType:@"json"];
} else if ([countryString isEqualToString:@"UK"]) {
filePath = [[NSBundle mainBundle] pathForResource:@"categoriesuk" ofType:@"json"];
} else if ([countryString isEqualToString:@"Italy"]) {
filePath = [[NSBundle mainBundle] pathForResource:@"categoriesit" ofType:@"json"];
} else if ([countryString isEqualToString:@"Spain"]) {
filePath = [[NSBundle mainBundle] pathForResource:@"categorieses" ofType:@"json"];
} else if ([countryString isEqualToString:@"Brazil"]) {
filePath = [[NSBundle mainBundle] pathForResource:@"categoriesbr" ofType:@"json"];
}
NSString *fileContent = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
//NSLog(@"File content: %@", fileContent);
// creating new parser
SBJSON *parser = [[SBJSON alloc] init];
// parsing the first level
NSDictionary *data = (NSDictionary *) [parser objectWithString:fileContent error:nil];
NSDictionary *menu = (NSDictionary *) [data objectForKey:@"menu"];
#ifdef DEBUG
NSLog(@"menu is %@",menu);
#endif
NSMutableArray *itemsTMP = [[NSMutableArray alloc] init];
NSData *jsonData = [NSData dataWithContentsOfFile:filePath];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:nil];
// NSLog(@"results File test %@",dict);
itemsTMP = [dict objectForKey:@"results"];
// NSLog(@"itemsTMPitemsTMP File test %@",itemsTMP);
self.arForTable = [itemsTMP copy];
[self.tableView reloadData];
}
#pragma mark - Table view data source
- (int)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.arForTable count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
[cell.textLabel setFont:[UIFont fontWithName: @"Asap-Bold" size: 14.0f]];
[cell.detailTextLabel setFont:[UIFont fontWithName: @"Asap-Bold" size: 14.0f]];
cell.selectedBackgroundView = [[UIView alloc] initWithFrame:CGRectZero];
cell.selectedBackgroundView.backgroundColor = [UIColor colorWithRed:204.0/255.0 green:56.0/255.0 blue:55.0/255.0 alpha:1];
}
UIImageView *cellAccessoryImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon-tick.png"]] ;
UIImageView *cellAccessoryNoneImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@""]] ;
if([_selectedItems containsObject:indexPath]){
cell.accessoryView = cellAccessoryImageView;
} else {
cell.accessoryView = cellAccessoryNoneImageView;
}
// Get item from tableData
NSDictionary *item = (NSDictionary *)[_arForTable objectAtIndex:indexPath.row];
// encoding fix
NSString *correctStringTitle = [NSString stringWithCString:[[item objectForKey:@"key"] cStringUsingEncoding:NSISOLatin1StringEncoding] encoding:NSUTF8StringEncoding];
cell.textLabel.text = [correctStringTitle capitalizedString];
NSNumber *num = [item objectForKey:@"id"];
cell.detailTextLabel.text = [num stringValue];
cell.detailTextLabel.hidden = YES;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
if([_selectedItems containsObject:indexPath]){
[_selectedItems removeObject:indexPath];
[self.categorySelected removeObject:[[self.arForTable objectAtIndex:indexPath.row] objectForKey:@"id"]];
string = [self.categorySelected componentsJoinedByString:@","];
[defaults setObject:string forKey:@"selectedCategoryTableString"];
NSLog(@"%@ defaults from did select remove categorySelected",[defaults stringForKey:@"selectedCategoryTableString"]);
NSLog(@"%@ STRING FROM contains / removeObj",string);
} else {
[_selectedItems addObject:indexPath];
[self.categorySelected addObject:[[self.arForTable objectAtIndex:indexPath.row] objectForKey:@"id"]];
NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
string = [self.categorySelected componentsJoinedByString:@","];
[defaults setObject:string forKey:@"selectedCategoryTableString"];
NSLog(@"%@ providerSelected from did select add ",self.categorySelected);
NSLog(@"%@ STRING FROM contains / addObj",string);
}
[tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
// [tableView reloadData];
}
-(void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:NO];
[self.navigationController setNavigationBarHidden:YES animated:NO];
self.navigationController.toolbarHidden = YES;
NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
// NSLog(@"ALL DEFAULTS %@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
NSLog(@"%@ defaults from view appear categorySelected",[defaults stringForKey:@"selectedCategoryTableString"]);
string = [defaults stringForKey:@"selectedCategoryTableString"];
NSLog(@"%@ STRING from will appear",string);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
同样在我在.h中的应用程序委托中:
@property (strong, nonatomic) NSMutableArray *selectedCategories;
在 .m 中:
`_selectedCategories = [NSMutableArray new];
在didFinishLaunchingWithOptions:
方法中
只是要清楚:
当视图再次出现时(如果我 nslog 输出),mutablearray 已被保存并被正确检索。可变数组仅在再次触摸 tablerow 时自行清除。感谢是否有人可以提供帮助。我已经坚持了一段时间了...