【问题标题】:NSPredicate search through NSMutableArrayNSPredicate 通过 NSMutableArray 搜索
【发布时间】:2014-10-04 08:29:23
【问题描述】:

我有一个视图控制器,它从我的 Web 服务中检索地址信息,将其存储在一个可变数组中,然后在表格视图中显示每个地址。我在同一个视图控制器上有一个搜索栏,我想搜索每个地址并显示结果。我有一个测试NSArray,但是我不确定我需要对filterContentForSearchText 函数做什么才能让它通过NSMutableArray 进行搜索。任何帮助表示赞赏。

对象类

//  Branches.h

@interface Branches : NSObject
@property (nonatomic, retain) NSString *BranchAddress;
@end

查看控制器类

//  ViewController.h

@interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UISearchDisplayDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@end

.

//  ViewController.m

#import "AFHTTPRequestOperationManager.h"
#import "ViewController.h"
#import "Branches.h"

@interface ViewController () {
    NSMutableArray *array;
}
@property (strong, nonatomic) NSArray *searchResults;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Initialize myArray
    array = [[NSMutableArray alloc] init];

    // Set POST parameters
    NSDictionary *parameters = @{@"key" : @"value"};

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:@"webservice_address" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        // Check to see if responseObject contains data
        if (responseObject != nil) {

            // Loop through JSON
            for (NSDictionary *dictionary in responseObject) {

                // Initialize object
                Branches *branches    = [[Branches alloc] init];
                branches.branchAddress = [dictionary objectForKey:@"Object"];
                // Add object to myArray
                [array addObject:branches];

                [self.tableView reloadData];
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];

}

#pragma Table View Methods

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        return [self.searchResults count];

    } else {
        return [array count];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    if (tableView == self.searchDisplayController.searchResultsTableView) {
        cell.textLabel.text = [self.searchResults objectAtIndex:indexPath.row];

    } else {
        cell.textLabel.text = [[array objectAtIndex:indexPath.row] BranchAddress];
    }
    return cell;

}

#pragma Search Methods

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
    NSArray *masterArray    = array;
    NSArray *searchResults  = [masterArray filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(Branches *evaluatedObject, NSDictionary *bindings) {
        //NSLog(@"%@", evaluatedObject.BranchAddress);
        return ([evaluatedObject.BranchAddress rangeOfString: searchText options:NSCaseInsensitiveSearch].location != NSNotFound);
    }]];
    NSLog(@" %i", searchResults.count);
    //[searchResults removeAllObjects];
    //[searchResults addObjectsFromArray:searchResults];

    //reload after this
    NSLog(@"%@", [searchResults objectAtIndex:0]);
}

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    [self filterContentForSearchText:searchString
                               scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
                                      objectAtIndex:[self.searchDisplayController.searchBar
                                                     selectedScopeButtonIndex]]];

    return YES;
}

@end

【问题讨论】:

    标签: ios objective-c uitableview nsmutablearray


    【解决方案1】:

    你可以试试这个

    - (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
    {
        NSArray *masterArray    = self.array; 
        NSArray *resultsArray  = [masterArray filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(Branches *evaluatedObject, NSDictionary *bindings) {
            return ([evaluatedObject.BranchAddress rangeOfString: searchText options:NSCaseInsensitiveSearch].location != NSNotFound);
        }]];
        //edited
        [self.searchResults removeAllObjects]; //self.searchResults should be mutable array 
        [self.searchResults addObjectsFromArray:resultsArray];//put the new values to searchResults
    
         //after this self.searchResults contains objects of filtered Branches u can get the values for example
         NSLog(@"%@", [[self.searchResults objectAtIndex:0] BranchAddress]);//self.searchResults contains objects of Branches not the string itself 
    
        //reload after this 
    } 
    

    【讨论】:

    • 我已经用你的代码更新了我的答案。数组计数确实发生了变化,这意味着代码部分工作。当我尝试打印数组中的第一个元素时,我得到 。这不应该打印地址字符串吗?表格视图上实际上没有显示任何结果。
    • 它正在对数组中的整个 Branches 对象进行排序,而不是它自己的地址,因此您需要打印地址,例如 `NSLog(@"%@", [[searchResults objectAtIndex:0] BranchAddress ]);` 还有为什么要投反对票...?
    • @user3626407 我编辑了答案检查它,然后投反对票..?
    • 谢谢珊 - 我没有给你投反对票。 [self.searchResults removeAllObjects]; [self.searchResults addObjectsFromArray:searchResults];两者都抛出错误。没有可见的接口,因为数组是不可变的。
    • 将 self.searchResults 数组更改为可变数组,因为该数组会随着用户输入不同的值而不断变化
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多