开发者

Memory Leaks - Returning NSMutableArray from class method containing Custom Objects

开发者 https://www.devze.com 2023-02-15 21:50 出处:网络
I am using DBManager Class to retrun data from SQlite database. The class contains methods which returns MutableArray by fetching it from database. like bellow ..

I am using DBManager Class to retrun data from SQlite database. The class contains methods which returns MutableArray by fetching it from database. like bellow ..

+ (NSMutableArray *) getSaleForYear : (NSString *) year {

    if ([DBManager openDBConnection]) {

        NSMutableArray * sales = [[NSMutableArray alloc] initWithCapacity:1];

        const char *q = "SELECT sales, quarter FROM sale where year like ? order by quarter";
        sqlite3_stmt *selectstmt;
        if (sqlite3_prepare_v2(database, q, -1, &selectstmt, NULL) == SQLITE_OK) {

            if(sqlite3_bind_text(selectstmt, 1, [year UTF8String] , -1, SQLITE_TRANSIENT) != SQLITE_OK){
                NSLog(@"bind error : %@", [NSString stringWithUTF8String: sqlite3_errmsg(database)]);
                return nil;
            }

            while(sqlite3_step(selectstmt) == SQLITE_ROW) {
                float sale = sqlite3_column_double(selectstmt, 0);
                    //NSString * quarter = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];
                NSString * quarter = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)];

                ChartData * b1 = [[ChartData alloc] initwithdata:quarter y:sale];
                [sales addObject:b1];
                [开发者_开发百科b1 release];
                [quarter release];
            }
        }

        sqlite3_finalize(selectstmt);
        [DBManager closeDBConnection];
        return [sales autorelease];
    }else {
        return nil;
    }
}

And I am calling the method like.

- (IBAction) getData {

    NSLog(@"getdata");

    if (arr != nil) {
        for (ChartData * cd in arr) {
            [cd release];
        }
        arr = nil;
        [arr release];
    }

    arr = [[DBManager getSaleForYear:@"2010-11"] copy];
    NSLog(@"count %d ", [arr count]);
}

This approach is creating memory leaks for iterative calls of the function. Please suggest cause of the leak and solution.


  1. You set arr = nil before releasing it, this the [arr release] has no effect
  2. You must not loop through the array and release each object (see fluchtpunkt comment below).
  3. No need to check arr == nil sending messages to nil is valid.

I'd write:

- (IBAction)getData {
    NSLog(@"getdata");

    [arr release];

    arr = [[DBManager getSaleForYear:@"2010-11"] copy];
    NSLog(@"count %d ", [arr count]);
}


you should probably invert these lines of code:

arr = nil;
[arr release];

this way:

[arr release];
arr = nil;
0

精彩评论

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

关注公众号