Textfields作为搜索栏崩溃

时间:2018-04-21 10:17:59

标签: ios objective-c iphone xcode

我正在使用此代码将textfiled作为搜索栏。这是我的代码。但我在textfield上的范围崩溃了。如果我开始输入然后崩溃。甚至无法处理区分大小写的文本

#import "ViewController.h"
#import "AFNetworking.h"
#import <QuartzCore/QuartzCore.h>

@interface ViewController ()
{
    NSMutableArray *countryArray;
    NSMutableArray *searchArray;
    NSString *searchTextString;
    BOOL isFilter;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    _countryView.hidden = true;
    self->countryArray = [[NSMutableArray alloc] init];
    [self makeRestuarantsRequests];
    _tableView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _tableView.layer.borderWidth = 1;
    _tableView.layer.cornerRadius=5;
   [self.searchTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];

}


-(void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self
                                                   name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - AFNetworking

-(void)makeRestuarantsRequests{

    NSURL *url = [NSURL URLWithString:@"example url"];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];


    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
                                                                                        success:^(NSURLRequest *request, NSHTTPURLResponse *response, id responseObject) {
                                                                                            self->countryArray = [responseObject objectForKey:@"data"];
                                                                                                                                                                                    [self.tableView reloadData];
                                                                                        }
                                                                                        failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id responseObject) {
                                                                                            NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
                                                                                        }];
    [operation start];

}
#pragma mark - Tableview Delegate and Datasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{


    if(isFilter)
    {
        return [searchArray count];
    }
    else
        return  [countryArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];


    NSDictionary *tempDictionary= [self->countryArray objectAtIndex:indexPath.row];


    if(isFilter)
    {
        cell.textLabel.text=[searchArray objectAtIndex:indexPath.row];
    }
    else
    {
         cell.textLabel.text = [tempDictionary objectForKey:@"name"];
    }

//     cell.textLabel.text = [tempDictionary objectForKey:@"name"];

    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
   [_SelectCountryButton setTitle:cell.textLabel.text forState:UIControlStateNormal];
    _countryView.hidden = true;

}

-(void)textFieldDidChange:(UITextField *)textField
{
    searchTextString=textField.text;
    [self updateSearchArray:searchTextString];
}

-(void)updateSearchArray:(NSString *)searchText
{
    if(searchText.length==0)
    {
        isFilter=NO;
    }
    else{

        isFilter=YES;
        searchArray=[[NSMutableArray alloc]init];
        for(NSString *string in countryArray){

            NSRange stringRange=[string rangeOfString:searchText options:NSCaseInsensitiveSearch];
            if(stringRange.location !=NSNotFound){

                [searchArray addObject:string];
            }
        }
        [self.tableView reloadData];}
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
#pragma mark UITextFieldDelegates


- (IBAction)SelectCountry:(id)sender {

    _countryView.hidden = false;

}



@end

出现崩溃错误:

由于未捕获的异常终止应用&#39; NSInvalidArgumentException&#39;,原因:&#39; - [__ NSDictionaryI rangeOfString:options:]:无法识别的选择器发送到实例0x10128b4f0

错误代码:

-(void)updateSearchArray:(NSString *)searchText
    {
        if(searchText.length==0)
        {
            isFilter=NO;
        }
        else{

            isFilter=YES;
            searchArray=[[NSMutableArray alloc]init];
            for(NSString *string in countryArray){

                NSRange stringRange=[string rangeOfString:searchText options:NSCaseInsensitiveSearch];
                if(stringRange.location !=NSNotFound){

                    [searchArray addObject:string];
                }
            }
            [self.tableView reloadData];}
    }

请帮帮我。我怎样才能解决这个问题。 提前谢谢!

更新:

{"response":true,"message":"country.","data":[{"id":1,"name":"Afghanistan"},{"id":2,"name":"Albania"},{"id":3,"name":"Algeria"},{"id":4,"name":"American Samoa"},{"id":5,"name":"Andorra"},{"id":6,"name":"Angola"}]}

1 个答案:

答案 0 :(得分:1)

我有很好的谓词方法

根据你的jsonResponse

 // so forEach loop should like this

 for(NSDictionary *Dic in CountryArray){
 NSString*str=[NSString stringWithFormat:@"%@",[dic objectForKey:@"name"]];
 }

  // well i am not using for each loop instead of that i have nsmutablearray name as  _searchArraySingle is same like your countryArray with predicate
 //  if you are using textfield in place of default Searchbar so use this then use NSPredicate 

 - (void)viewDidLoad {
[super viewDidLoad];

    [[NSNotificationCenter defaultCenter]
 addObserver:self
 selector:@selector(textFieldTextDidChangeOneCI:)
 name:UITextFieldTextDidChangeNotification
 object:searchTxt];
SearchBar.delegate = (id)self;

}


-(void)textFieldTextDidChangeOneCI:(NSNotification *)notification {
UITextField *textfield=[notification object];
[self predicatChangeText:textfield.text];
// NSLog(@"%@",textfield.text);

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {

[textField resignFirstResponder];

return NO;
}

-(void)predicatChangeText:(NSString*)text{


 //   myJSON.array
 NSPredicate *predicateString = [NSPredicate predicateWithFormat:@"%K    contains[cd] %@", @"name", text];
_filteredArray = [NSMutableArray arrayWithArray:[_searchArraySingle filteredArrayUsingPredicate:predicateString]];

NSLog(@"_filteredArray=%lu",(unsigned long)[_filteredArray count]);

[self.tableView reloadData];

 }

 - (IBAction)cancleSearch:(id)sender {
searchTxt.text=@"";
if (_filteredArray) {
    _filteredArray=nil;
  }

 [self.searchTxt resignFirstResponder];
_filteredArray = myJSON.array;
[self.tableView reloadData];
 }

这可能会帮助你!!!!好运

相关问题