views:

120

answers:

3

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.

+5  A: 

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];
}
Dave DeLong
I did, but instruments still reports a leak.
José Joel.
@José - perhaps your `myClass` object itself is never getting deallocated?
Dave DeLong
Then you are retaining it somewhere else.
bbum
A: 

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.

St3fan
@interface myClass : NSObject { NSMutableArray *classMember;}
José Joel.
The code is incredibly short and simple, how can it be more specific ?!. I'm trying to understand WHY instruments considers it a memory leak, when it isn't.
José Joel.
@St3fan other than the missing `- (id)` before the method selector, his init method is perfectly fine.
Dave DeLong
`(self = [super init]) != nil` is redundant. When `self = [super init]` returns nil, the conditional will fail because nil==0;
TechZen
@TechZen I don't care if it is redundant, it is a style I use. Just like I prefer (foo == NO) vs (!foo) or (foo == YES) vs (foo).
St3fan
+1  A: 

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.

TechZen
This code will in fact leak. initWithCapacity: returns a retained object, which is then again retained when you set the property. You should either append autorelease when you create the array, or use [NSMutableArray arrayWithCapacity:1], which will return an autoreleased object.
Felixyz