在第二次尝试时使用NSPredicate过滤数组导致exc_bad_access

时间:2012-02-22 03:08:22

标签: iphone objective-c ios nsarray nspredicate

我使用以下代码填充UITableViewController

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    NSString *selectedWord;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    ResultDetail *detail = [[[GameStore defaultStore] currentResultDetail] objectAtIndex:[indexPath row]];

    if([[detail selectedWord] isEqualToString:@"  "])
    {
        selectedWord = @" selected: n/a";
    }
    else{
        selectedWord = [NSString stringWithFormat:@" selected: %@", [[detail selectedWord] substringFromIndex:4]];
    }
    [[cell textLabel] setText:[NSString stringWithFormat:@" %@ (score: %d/4)",[detail word],[detail score]]];
    [[cell detailTextLabel] setText:selectedWord];

    detail = nil;
    [detail release];
    selectedWord = nil;
    [selectedWord release];

    return cell;
}

上面的代码运行正常,因为之前没有请求currentResultDetail的值。

以下是currentResultDetail的代码

- (NSArray *)currentResultDetail {

    NSLog(@"predicate: resultid == %d", [[GameStore defaultStore] currentResultId]);
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"resultId == %d", [[GameStore defaultStore] currentResultId] ];
    NSArray *filtered  = [[[GameStore defaultStore] allResults] filteredArrayUsingPredicate:predicate]; // failed here but only if currentResultId has been requested before. 

    predicate = nil;
    [predicate release];
    return [[filtered objectAtIndex:0] resultDetails];
}

上述代码在以下行中失败:

NSArray *filtered  = [[[GameStore defaultStore] allResults] filteredArrayUsingPredicate:predicate];

所以基本上如果用户按顺序请求currentResultId 1,2,3,4,5,6,7的currentResultDetail,它运行正常。但如果他们要求1,2,3,4,5,1就会崩溃。

指出为什么会发生这种情况的指针?

1 个答案:

答案 0 :(得分:2)

您的谓词将返回自动释放。不要手动释放它,否则当autoreleasepool尝试释放它时你会崩溃。