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:
- Potential leak of an object allocated on line 203
- Method returns an Objective-C object with a +1 retain count (owning reference)
- Object returned to caller as an owning reference (single retain count transferred to caller)
- Object allocated on line 203 is returned from a method whose name ('errorFromOriginalError:error:') does not contain 'copy' or otherwise starts with 'new' or 'alloc'. This violates the naming convention rules given in the Memory Management Guide for Cocoa (object leaked)
- Potential null dereference. According to coding standards in 'Creating and Returning NSError Objects' the parameter 'error' may be null
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.
You are making a copy of originalError, but your function name implies that the returned object will be autoreleased. Try
return [[originalError copy] autorelease];
[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];
精彩评论