winsmith
winsmith

Reputation: 21572

What is the memory management problem with this bit of code?

The XCode analyzer tells me there is a problem at line 4 — return [originalError copy]; — but I don't see it. Help me please?

- (NSError *)errorFromOriginalError:(NSError *)originalError error:(NSError *)secondError
{
    if (secondError == nil) {
        return [originalError copy];
    }
    // ...
}

The problem description is:

The third issue seems to suggest I should either change the name or the behaviour of the method further. Any suggestions on that? The method is derived from the errorFromOriginalError:error: method described in Apple's Core Data Validation document. Its purpose is to combine originalError and secondError so that secondError is a sub-error of originalError.

My addition tries to ensure that the method still works if there is no actual secondError. Since a new error object is created if secondError is not nil, I wanted to recreate that in the case displayed above by simply copying the error object.

Upvotes: 0

Views: 214

Answers (2)

jrturton
jrturton

Reputation: 119242

You are making a copy of originalError, but your function name implies that the returned object will be autoreleased. Try

return [[originalError copy] autorelease];

Upvotes: 2

Tom Jefferys
Tom Jefferys

Reputation: 13310

[originalError copy] creates a new object with a retain count set to 1. It would then be the responsibility of the calling method to release that object. If you're doing this then it isn't necessarily a problem, but it's probably a better ideas to autorelease it.

ie

return [[originalError copy] autorelease];

Upvotes: 1

Related Questions