NSPredicate崩溃

时间:2013-07-29 20:00:10

标签: ios objective-c uisearchbar nspredicate

在searchBar中,我有以下代码

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    self.filteredResults = [[NSMutableArray alloc] init];
    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"(%K == %@)", field1, field2];
    self.filteredResults = (NSMutableArray *)[originalArray filteredArrayUsingPredicate:predicate];
}

编辑:

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    originalArray = [[NSArray alloc] initWithContentsOfFile:path];
    return YES;
}

在我第二次运行谓词时,程序在self.fiteredResults消息中的searchBarSearchButtonClicked:searchBar分配时崩溃。如果我包含[self.filteredResults removeAllObjects],那么程序会在那里崩溃,因此它被删除了,并且在第二次执行搜索时它仍然无法运行。这段代码中的任何内容都会引起崩溃,还是我应该在其他地方寻找?提前谢谢。

3 个答案:

答案 0 :(得分:1)

这一行:

originalArray = [[NSFileManager defaultManager] fileExistsAtPath:path];

因为您尝试将BOOL设置为数组属性。


你应该制作一个可变数组的副本:

self.filteredResults = [[originalArray filteredArrayUsingPredicate:predicate] mutableCopy];

答案 1 :(得分:0)

正确分配了原始数组

完整的工作代码:

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];

    NSString* documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString* path = [documentsDirectory stringByAppendingPathComponent:@"plist.plist"];

    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        self.arrayFromCloud = [[NSArray alloc] initWithContentsOfFile:path];
    } 

    eventFromCloud = [[NSMutableArray alloc] init];

    for (NSDictionary* dic in self.arrayFromCloud) {
        [eventFromCloud addObject:[dic valueForKey:@"event"]];
    }

    [eventFromCloud removeObjectAtIndex:0];

    self.filteredResults = [[NSMutableArray alloc] init];

    searchBar.placeholder = @"SEARCH";

    // Filter the array using NSPredicate
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(%K == %@)", @"venue name", @"starbucks"];
    self.filteredResults = [[eventFromCloud filteredArrayUsingPredicate:predicate] mutableCopy];

    searchBar.text = nil;
    self.arrayFromCloud = nil;
    eventFromCloud = nil;
    self.filteredResults = nil;

}

我让这段代码工作的唯一方法是必须分配/初始化中间数组,并在搜索时第二次使用结果数组。最初甚至没有想到可能是他们造成了这个错误。

答案 2 :(得分:-1)

您编写谓词的方式存在问题。数组中的对象不包含“field1”属性。