UISearchBar和NSMutableArray的问题

时间:2011-08-13 04:04:55

标签: iphone objective-c ios nsarray uisearchbar

我有一个带有搜索栏的tableview。我想搜索我的整个核心数据库。

我在这里将所有内容加载到一个数组中:

NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Entity" inManagedObjectContext:managedObjectContext]; 
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease]; 
[request setEntity:entityDescription]; 
NSError *error = nil; 
NSArray *array = [managedObjectContext executeFetchRequest:request error:&error];   
self.myArray = array;

我正在使用此方法进行搜索,但收到错误:

- (void) searchTableView {

    NSString *searchText = searchBar.text;
    NSMutableArray *searchArray = [[NSMutableArray alloc] init];

    for (NSDictionary *dictionary in myArray)
    {
        NSString *value = [dictionary objectForKey:@"name"];
        [searchArray addObject:value];
    }

    for (NSString *sTemp in searchArray)
    {
        NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];

        if (titleResultsRange.length > 0)
            [copyListOfItems addObject:sTemp];
    }
    [searchArray release];
    searchArray = nil;
}

但是当我搜索时,我发现了崩溃:

MedicalCode *code = [self.copyListOfItems objectAtIndex:indexPath.row]; 
cell.codeLabel.text = code.description;

错误:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ICD9Disease objectForKey:]: unrecognized selector sent to instance 0x1be6e0'

2 个答案:

答案 0 :(得分:5)

你收到错误是因为你要求一个对象,但是你正试图在行中设置一个字符串:

NSString *value = [dictionary objectForKey:@"name"];

由于你得到一个字符串而不是一个对象,你需要使用的是valueForKey

    NSString *value = [dictionary valueForKey:@"name"];

答案 1 :(得分:0)

看起来您期望获取请求返回字典,但它实际上返回了ICD9Disease类的实例。