Fran Sevillano
Fran Sevillano

Reputation: 8163

NSData memory leak

Instruments is showing that i get a memory leak right there:

-(id) copyWithZone: (NSZone *) zone
{ 
    Layer *copy = [[Layer allocWithZone:zone]init];
    NSData *imageData = [[NSData alloc]initWithData:_image];
    copy.image = imageData;
    [imageData release];

    return copy;
}

The image property is declared as it follows:

@property (nonatomic, retain) NSData *image;

Here is a screenshot of instruments, to prove that i am not lying.

Image snapshot

Anyone see a problem in there?

Upvotes: 1

Views: 1142

Answers (3)

Fran Sevillano
Fran Sevillano

Reputation: 8163

Here is how we solved it, following the instructions given here.

-(id) copyWithZone: (NSZone *) zone
{
    Layer *copy = [[Layer allocWithZone:zone]init];
    copy->_image=nil;
    [copy setImage:[self image]];
    return copy;
}

Upvotes: 1

DarkDust
DarkDust

Reputation: 92335

The Leaks instruments shows you where an object originated, not where it "leaked". So somewhere in your code you'll have something like this:

MyClass *obj = [otherObj copy]; // or copyWithZone:

But you're not releasing or autoreleasing obj and thus create a leak.

In Objective-C, convention tells you a method should return an autoreleased object, except for methods that start with alloc, new, copy or mutableCopy. These method must return a retained object instead and the receiver is the owner and thus responsible for releasing them.

See Memory Management Policy in Apple's memory management guide.

Upvotes: 1

beryllium
beryllium

Reputation: 29767

- (id)copyWithZone:(NSZone *)zone{
    Layer *copy = [[[self class] allocWithZone: zone] init];
    [copy setImage:[self image]];

    return copy;
}

Upvotes: 0

Related Questions