这是我的数组
@property (nonatomic, strong) NSMutableArray *searchResults;
我在viewDidLoad函数中初始化它。我想在搜索栏中的当前输入更改时从此数组中删除所有对象,并使用新元素添加填充它。 但是当我做的时候
[self.searchResults removeAllObjects];
它不会添加新元素。将数组返回self.searchResults
也是如此但是当我不从数组中删除元素并附加元素时,它会添加没有问题的元素。我真的很难搞清楚什么是错的。
viewDidLoad func
- (void) viewDidLoad {
[super viewDidLoad];
self.searchBar.delegate = self;
self.searchBar.showsCancelButton = YES;
self.tableView.delegate = self;
self.tableView.dataSource = self;
self.searchResults = [[NSMutableArray alloc] init];
[self searchHandler:self.searchBar];
}
这里是添加新元素。
- (NSMutableArray *)getProductList: (NSString *)text withArray: (NSMutableArray *) arrayResult{
[self.searchResults removeAllObjects];
[manager POST:url parameters:parameter
success:^(AFHTTPRequestOperation *operation, id responseObject){
NSLog(@"Length: %lu", (unsigned long)[responseObject count]);
int length = [responseObject count];
NSString *key;
for (int i=0; i<length; i++) {
key = [NSString stringWithFormat:@"%d", i];
[self.searchResults addObject:responseObject[key]];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
}
检查数组
- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText {
NSLog(@"changed text: %@", searchText);
//[searchResults removeAllObjects];
self.searchResults = [self getProductList:searchText withArray:self.searchResults];
NSLog(@"Length of current array: %lu", (unsigned long)[self.searchResults count]);
for (NSString *item in self.searchResults) {
NSLog(@"%@", item);
}
[self.tableView reloadData];
}
答案 0 :(得分:0)
您设置了searchResults
self.searchResults = [self getProductList:searchText withArray:self.searchResults];
但是getProductList
没有返回数组。你得到警告吗?如果没有,我怀疑你只是在返回时将其设置为nil
此外,getProductList
是异步的,但您只是在返回时尝试加载表数据。
做一些更像这样的事情:
- (NSMutableArray *)getProductList: (NSString *)text withArray: (NSMutableArray *) arrayResult{
[self.searchResults removeAllObjects];
[manager POST:url parameters:parameter
success:^(AFHTTPRequestOperation *operation, id responseObject){
NSLog(@"Length: %lu", (unsigned long)[responseObject count]);
int length = [responseObject count];
NSString *key;
for (int i=0; i<length; i++) {
key = [NSString stringWithFormat:@"%d", i];
[self.searchResults addObject:responseObject[key]];
}
[self.tableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
}
- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText {
[self getProductList:searchText withArray:self.searchResults];
}
这应该被清理得更多(删除withArray参数 - 你甚至不用它)。
此时请确保self.searchResults
不是零。