内存泄漏涉及NSString

时间:2009-04-08 22:04:54

标签: iphone objective-c cocoa-touch sqlite

我在应用程序中找不到内存泄漏的原因。我发现通过仪器存在内存泄漏,而且我调用函数的次数多于发生更多内存泄漏。因此很明显会发生内存泄漏。

这是我的代码。 对象:

@interface WordObject : NSObject
{
    int word_id;
    NSString *word;
}

@property int word_id;
@property (copy) NSString *word;

@end

用于填充UITableView的方法:

-(void) reloadTableData {
        [tableDataArray removeAllObjects];

        for (int i = 0; i <= 25; i++)
        {
            NSMutableArray *words_in_section = [ [NSMutableArray alloc] init];
            [tableDataArray addObject:words_in_section];
            [words_in_section release];
        }

        WordObject *tempWordObj;

        int cur_section;

        while ( tempWordObj = [ [WordsDatabase sharedWordsDatabase] getNext] )
        {   
            cur_section = toupper([ [tempWordObj word] characterAtIndex:0 ] ) - 'A';

            NSMutableArray *temp_array = [tableDataArray objectAtIndex:cur_section];
            [temp_array addObject:tempWordObj];
            [tableDataArray replaceObjectAtIndex:cur_section withObject:temp_array];
        }

        [mainTableView reloadData];

        [mainTableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
    }

获取细胞内容:

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

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


    WordObject *tempWordObj = [ [tableDataArray objectAtIndex:[indexPath section] ] objectAtIndex:[indexPath row] ];

    if (!tempWordObj)
    {
        return cell;
    }

    cell.text = [tempWordObj word];

    return cell;
}

这是我如何清理内存:

-(void) freeMemory
{   
    if (tableDataArray)
    {
        [tableDataArray release];
        tableDataArray = nil;
    }
}

从reloadTableData调用的函数:

    -(WordObject*) getNext {
    if(sqlite3_step(getStmt) == SQLITE_DONE)
    {
        sqlite3_reset(getStmt);
        return nil;
    }


    WordObject *tempWord = [ [WordObject alloc] init];
    tempWord.word_id = sqlite3_column_int(getWordsStmt, 0);

    tempWord.word = [NSString stringWithUTF8String:(char *)sqlite3_column_text(getWordsStmt, 1)]; //Here a leak occurs

    return [tempWord autorelease];
}

泄漏的对象是[WordObject word]。

我将非常感谢能够帮助我解决这个问题的任何人。

1 个答案:

答案 0 :(得分:4)

将此方法添加到WordObject:

- (void)dealloc {
    [word release];
    [super dealloc];
}

此代码确保在删除WordObject实例时释放属性word


我很确定此代码也属于dealloc方法。顺便说一句,您不需要tableDataArray = nil

- (void)freeMemory
{   
    if (tableDataArray)
    {
        [tableDataArray release];
        tableDataArray = nil;
    }
}