views:

206

answers:

1

So I am trying to fix this really annoying bug. If I filter my array like the ideal version with NSPredicate, I will get EXC_BAD_ACCESS because it tries to call release on the object passed in as the delegate an extra time. If I filter with the working version, it works fine. I thought these two implementations were identical. Where am I going wrong? I know the predicate way is the way to go, just can't get it to work correctly.

// Ideal version
- (NSArray *)foosWithDelegate:(id)delegate {
    return [foos filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"delegate = %@", delegate]];
}

// Working version
- (NSArray *)foosWithDelegate:(id)delegate {
    NSMutableArray *results = [[NSMutableArray alloc] init];
    for (MYFoo *foo in foos) {
     if (foo.delegate == delegate) {
      [results addObject:foo];
     }
    }

    if ([results count] == 0) {
     [results release];
     return nil;
    }

    return [results autorelease];
}

foos is an ivar. The MYFoo class has a property for delegate that is assign. The issue still happens even if foos is empty.

+1  A: 

In your PredicateTestViewController's dealloc method, you should be releasing foos, not deallocating them.

// Your code in PredicateTestViewController.m
- (void)dealloc
{
    [foos dealloc];
    [super dealloc];
}

// Your new code in PredicateTestViewController.m
- (void)dealloc
{
    [foos release];
    [super dealloc];
}
nall
+1 totally correct.
Dave DeLong
This was a typeo and has nothing to do with the issue in the question.
Sam Soffes
The typeo has been corrected http://github.com/samsoffes/predicate-test/commit/cb4f6bde6cabc9fc4a57d05b7562ea2a154a9ff9
Sam Soffes