开发者

Problem with allocating memory for an Objective-C data object

I've been programming objective-C for a few months now and have done pretty well so far without having to post any questions. This would be my first. The problem is that I'm getting a memory leak warning from a data object in one of it's methods. I can see that the problem is that I'm sending an alloc to it without releasing it, but I don't know how else to get it to retain the object in memory. If I take the alloc out, the program crashes. If I leave it in, it leaks memory. Here is the method in question:

+ (id) featureWithID:(int)fID name:(NSString*)fName secure:(int)fSecure {
Feature *newFeature = [[self alloc] init];
newFeature.featureID = fID;
newFeature.featureName = fName;
newFeature.featureSecure = fSecure;

return [newFeature autorelease];

}

This method is called by another method in my view controller. This method is as follows:

+ (NSMutableArray*) createFeatureArray {

NSString *sqlString = @"select id, name, secure from features";
NSString *file = [[NSBundle mainBundle] pathForResource:@"productname" ofType:@"db"];
sqlite3 *database = NULL;
NSMutableArray *returnArray = [NSMutableArray array];

if(sqlite3_open([file UTF8String], &database) == SQLITE_OK) {

    const char *sqlStatement = [sqlString UTF8String];
    sqlite3_stmt *compiledStatement;

    if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {

        while(sqlite3_step(compiledStatement) == SQLITE_ROW) {

            Feature *myFeature = [Feature featureWithID:sqlite3_column_int(compiledStatement,0) 
                                                   name:[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)]
                                                 secure:sqlite3_column_int(compiledStatement,2)];

            [returnArray addObject:myFeature];

        }
    }
    // Release the compiled statement from memory
    sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
return returnArray;

}

I have tried s开发者_StackOverflow社区everal things, such as creating a featureWithFeature class method, which would allow me to alloc init the feature in the calling method, but that crashed the program also.

Please let me know if you need any clarification or any other parts of the code. Thank you in advance for your help.

UPDATE: 4/14/2011

After reading the first two responses I implemented the suggestion and found that the program is now crashing. I am at a complete loss as to how to track down the culprit. Hoping this helps, I am posting the calling method from the view controller as well:

- (void)setUpNavigationButtons {
// get array of features from feature data controller object
NSArray *featureArray = [FeatureController createFeatureArray];
int i = 0;


for (i = 0; i < [featureArray count]; i++) {
    Feature *myFeature = [featureArray objectAtIndex:i];
    CGRect buttonRect = [self makeFeatureButtonFrame:[featureArray count] withMember:i];

    UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [aButton setFrame:buttonRect];

    [aButton addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside];
    [aButton setTitle:[NSString stringWithFormat:@"%@",myFeature.featureName] forState:UIControlStateNormal];
    aButton.tag = myFeature.featureID;

    [self.view addSubview:aButton];

}

}

NOTE: These methods are posted in reverse of the order they are invoked. This last method calls the second method, which in turn, calls the first.

UPDATE: I've updated these functions to show what is in there now: Below, I will post the header files for the object - maybe that will help

@interface Feature : NSObject {
    int         featureID;
    int         featureSecure;
    NSString    *featureName;
}

@property (nonatomic, assign) int featureID;
@property (nonatomic, assign) int featureSecure;
@property (nonatomic, retain) NSString *featureName;

- (id) init;

- (void) dealloc;

+ (id) featureWithID:(int)fID name:(NSString*)fName secure:(int)fSecure;



@end

@interface FeatureController : NSObject {

}


- (id) init;

- (void) dealloc;

+ (NSMutableArray*) createFeatureArray;

+ (Feature*) getFeatureWithID:(int)fetchID;

@end


Convenience methods should follow the convention of returning autoreleased objects. Change this:

+ (id) featureWithID:(int)fID name:(NSString*)fName secure:(int)fSecure {
Feature *newFeature = [[self alloc] init];
...    
return newFeature;
}

to:

+ (id) featureWithID:(int)fID name:(NSString*)fName secure:(int)fSecure {
Feature *newFeature = [[self alloc] init];
...    
return [newFeature autorelease];
}


The name of your method - +featureWithID:name:secure: - indicates that it returns an object that the caller does not own. Instead, it is returning an object that has been retained, that the caller therefore owns and must release. To fix this (and your leak), simply replace return newFeature with return [newFeature autorelease].

There's nothing more you need to do, because your own code doesn't need a long-lasting ownership claim, and the array to which you're adding the object will manage its own ownership claim over it.


In +createFeatureArray, you’re over releasing the array:

+ (NSMutableArray*) createFeatureArray {
    …
    NSMutableArray *returnArray = [[[NSMutableArray alloc] init] autorelease];
    …
    return [returnArray autorelease];
}

In the first line, you used +alloc, so you own the array. Then you used -autorelease, so you do not own the array any more. This means that you shouldn’t send -release or -autorelease to it, which you are doing in the return line.

You can fix that by changing those lines to:

+ (NSMutableArray*) createFeatureArray {
    …
    NSMutableArray *returnArray = [NSMutableArray array];
    …
    return returnArray;
}

Also, unless it is relevant to callers that the array is mutable, you should change that method to return NSArray instead of NSMutableArray. You could keep your code as is, i.e., return a mutable array even though the method declaration states that the return type is NSArray.


As for your convenience constructor, there are essentially two choices depending on whether you want to return an owned or a non-owned object:

  • if you want to return an owned object, allocate it with +alloc or +new and return it without autoreleasing it. Your method name should contain new, e.g. +newFeatureWithId:…

  • if you want to return an object that’s not owned by the caller, allocate it with +alloc or new and autorelease it before/upon returning it to the caller. Your method name should not contain new, alloc, or copy.


In -setUpNavigationButtons, you obtain a non-owned array via +createFeatureArray, allocate a mutable array based on it, and release the mutable array without adding or removing elements from it. A mutable array makes sense when you need to add/remove elements. If you don’t have this need, you could change your method to:

- (void)setUpNavigationButtons {
// get array of features from feature data controller object
NSArray *featureArray = [FeatureController createFeatureArray];
…
// [featureArray release];

You’d remove that [featureArray release] since you do not own featureArray inside that method.


Edit: In -setUpNavigationButtons, you’re retaining the button you create and soon after you’re releasing it. In that particular method, those are idempotent operations — they aren’t wrong per se but are not necessary at all. You could replace that code with

UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
…
[self.view addSubview:aButton];
// [aButton release];

i.e., do not retain it and do not release it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜