0

I made a subclass of NSCell and overrided the setObjectValue function to achieve my need.Things are fine except there is a leak problem. The setObjectValue function of NSCell seems wont release its original object.

The object I give the class is a customize object which conform to the NSCopying Protocol and implemented the copyWithZone function as below

- (void)setObjectValue:(id < NSCopying >)object {

    // I tried to use [[self objectValue] release]; here but the app crashed 

    [super setObjectValue:object];

    //---- other iniatizlize here ---   
}

.

- (id)copyWithZone:(NSZone *)zone {
    MapComponent *newCopy = [[MapComponent allocWithZone:zone] initWithType:self.componentType];
    newCopy.myImage = self.myImage;
    return newCopy;
}

I have found the same problem here. There is no answer but may better discribe my situation.

MathieuF
  • 3,130
  • 5
  • 31
  • 34
mr.Pony
  • 257
  • 3
  • 15

1 Answers1

2

Try this :

- (id)copyWithZone:(NSZone *)zone {
    MapComponent *newCopy = [[[MapComponent allocWithZone:zone] initWithType:self.componentType] autorelease];
    newCopy.myImage = self.myImage;
    return newCopy;
}
MathieuF
  • 3,130
  • 5
  • 31
  • 34
  • 2
    You should not return an `autorelease` value from a copy method! – Richard Apr 14 '11 at 20:19
  • Another problem here is that you are using the accessor `newCopy.myImage`, which initially has the same **pointer value** has `self.myImage`. What you want to do is direct pointer access: `newCopy->myImage = nil; newCopy.myImage = self.myImage;` Otherwise, `newCopy` will `release` self's `myImage` when it tries to make a copy of it. – Richard Apr 14 '11 at 20:21