开发者

analyze show copywithzone is leaking, is it false alarm?

开发者 https://www.devze.com 2023-03-10 04:18 出处:网络
In my app I want to copy a custom class from one array to another array. So I implemented copyWithZone for this class. Xcode analyze warning me that every line with [alloc] or [copy] are leaking memor

In my app I want to copy a custom class from one array to another array. So I implemented copyWithZone for this class. Xcode analyze warning me that every line with [alloc] or [copy] are leaking memory. How can I tell if it's really leaking or it's the copied instance that I need?

@implementation MyClass

- (id)copyWithZone:(NSZone *)zone {

    MyClass *copy = [[MyClass allocWithZone开发者_开发百科:zone] init];
    if (copy){
        copy.uniqueId = [uniqueId copy];
    }

    return copy; 
}


Is your uniqueId property declared as a retain property? If so, this line is leaking:

copy.uniqueId = [uniqueId copy];

Change it to:

copy.uniqueId = [[uniqueId copy] autorelease];


It's not quite right.

The line

copy.uniqueId = [uniqueId copy];

should probably be

copy.uniqueId = self.uniqueId;

That way you'll get correct semantics for the property no matter if it is declared as copy, retain or assign.

Also, I wouldn't bother with the test for copy != nil. Sending setUniqueId: to nil is a no op.

Edit

By the way

copy.uniqueId = [uniqueId copy];

leaks if the property is retain or copy since [uniqueId copy] gives you an object you own and you don't release or autorelease it before the end of the scope.

0

精彩评论

暂无评论...
验证码 换一张
取 消