简体   繁体   中英

Is this a memory leak?

I have something similar to this.

initMyclass {
 if (self= [super init]) {
   classMember = [[NSMutableArray alloc] init];
 }
 return self;
}

Instruments reports a leak there.

I'm leaking memory there ? If not, xcode reports false memory leaks ?

Thanks.

Instruments is reporting the leak there because you're not releasing the object elsewhere. You need to have [classMember release] in that class's dealloc method:

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

This is why you should use properties or explicit accessors.

If you had this:

@interface myObject : NSObject
{
    NSMutableArray *classMembers;
}
@property(nonatomic, retain)  NSMutableArray *classMembers;

@end

@implementation myObject
@synthesize classMembers;

-(id) init{
    if (self=[super init]) {
        self.classMembers=[[NSMutableArray alloc] initWithCapacity:1];
    }
    return self;
}//-------------------------------------(id) init------------------------------------

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

@end

You would not (and should not ever) have to miss around with the retention of a property. This eliminates all leaks and over-releasing of properties.

If the property's object leaks, then you know automatically it is being retained in another object other than the instance of the class containing the property.

Is it a class or instance member? Show us the @interface for this class.

Also, initMyClass .. or something .. is not a proper init method. It's signature should be of the form:

- (id) init {
    if ((self = [super init]) != nil) {
        someInstanceVariable = [NSMutableArray new];
    }
    return self;
}

Be more specific when you ask a question here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM