Is it a memory leak?

I have something like this.

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

Tools report a leak there.

Am I losing my memory there? If not, does xcode report false memory leaks?

Thank.

+3
source share
3 answers

Tools report a leak there because you are not releasing the object elsewhere. You must have a method [classMember release]in this class dealloc:

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

This is why you should use properties or explicit accessors.

If you have 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 should not (and should never) skip around with the preservation of property. This eliminates all leaks and excessive release of properties.

, , , , .

+1

Is this a member of a class or instance? Show us @interfacefor this class.

Also, initMyClass.. or something .. is not a proper init method. His signature should be as follows:

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

More specifically, when you ask a question here.

-2
source

Source: https://habr.com/ru/post/1732877/


All Articles