Ios 文本字段作为搜索栏正在崩溃

Ios 文本字段作为搜索栏正在崩溃,ios,objective-c,iphone,xcode,Ios,Objective C,Iphone,Xcode,我使用这个代码作为搜索栏。这是我的代码。但我在文本字段上的范围会崩溃。如果我开始输入,它就会崩溃。甚至不能处理区分大小写的文本 #import "ViewController.h" #import "AFNetworking.h" #import <QuartzCore/QuartzCore.h> @interface ViewController () { NSMutableArray *countryArray; NSMutableArray *searchAr

我使用这个代码作为搜索栏。这是我的代码。但我在文本字段上的范围会崩溃。如果我开始输入,它就会崩溃。甚至不能处理区分大小写的文本

#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
请帮帮我。我怎样才能解决这个问题。 提前谢谢

更新:

{"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"}]}

我对谓词有很好的理解

根据你的回答

 // 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];
 }

也许这会帮到你!!!!GoodLuck

错误是说
for中的
string
实际上是
NSDictionary
对象,而不是
NSString
对象。既然你做了
self->countryArray=[responseobjectforkey:@“data”]
,我猜
[responseobjectforkey:@“data”]
NSDictionary
的一个
NSArray
。那么,我该如何重新更改它使其工作呢..我完全搞不清楚
[responseobjectforkey:@“data”]
.u表示从服务器上响应数据?这就是我的意思。如果您不告诉我们响应是什么以及如何调整代码,我们将无法帮助您。
 // 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];
 }