开发者

NSMutableArray, removeFromArray and release, why does this crash?

开发者 https://www.devze.com 2023-02-05 11:20 出处:网络
The fol开发者_开发技巧lowing method is used to cleanup a journal of its empty pages at the end.

The fol开发者_开发技巧lowing method is used to cleanup a journal of its empty pages at the end.

// self.pages property declaratioN, this is on the header
@property(nonatomic, retain) NSMutableArray *pages;

// method that crashes
- (void)cleanup {

    NSMutableArray *pagesToRemove = [[NSMutableArray alloc] init];
    for (int n = [self.pages count]-1; n >= 0; n--) {
        JournalPage *page = [self.pages objectAtIndex:n];
        if (![page isEmpty]) {
            break;
        } else {
            if (([self.pages count] - ([pagesToRemove count] + 1) > 2)) {
                [pagesToRemove addObject:page];
            } else {
                break;
            }               
        }

    }

    if ([pagesToRemove count] % 2 != 0) {
        [pagesToRemove removeLastObject];
    }
    [self.pages removeObjectsInArray:pagesToRemove];
    [pagesToRemove release]; // this line makes the app crash
}       

Releasing pagesToRemove causes a crash. The crash happens also if I remove the [pageToRemove release], and use instead autorelease when I alloc/init the NSMutableArray instance.

Without releasing pageToRemove the code works, but I see a leak, and clang analyzer also sees it.

Is this code leaking; if not, why?


There's a typo in your crasher:

[pageToRemove release]; // this line makes the app crash

Note that it says pageToRemove, not pagesToRemove. ;)

0

精彩评论

暂无评论...
验证码 换一张
取 消