NSMutableDictionary - "Incorrect decrement of the reference count of an object..."
I have a property in my header file as
@property (nonatomic,retain) NSMutableDictionary* e;
and in my viewDidLoad: method allocated it like
self.e = [[NSMutableDictionary alloc] initWithContentsOfURL:myURL];
.
The XCode static analyser is triggered, and says 'Potential leak of an object...'
obviously. But when I release the object ([self.e release]
in dealloc) the error persists, but now it also is saying that there is an "incorrect decrement of the reference count", and that this object is not owned by the caller (my viewController).
The 'i开发者_JAVA百科ncorrect decrement...' error goes away when I replace [self.e release]
with simply [e release]
. But the former error about potential leak is still there. What is the problem?
This statement:
self.e = [[NSMutableDictionary alloc] initWithContentsOfURL:myURL];
is over-retaining the object. Both alloc-init and the property retain the object.
In terms of ownership, you own the object returned by alloc-init and by sending it a retain message in the property accessor you claim ownership of it again, which results in the object being over-retained.
You can use a convenience constructor, which returns an object yo do not own, and let the property accessor claim ownership of it:
self.e = [NSMutableDictionary dictionaryWithContentsOfURL:myURL];
Or make use of autorelease:
self.e = [[[NSMutableDictionary alloc] initWithContentsOfURL:myURL] autorelease];
Or use a temporary variable:
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] initWithContentsOfURL:myURL];
self.e = tempDict;
[tempDict release];
The problem is:
self.e = [[NSMutableDictionary alloc] initWithContentsOfURL:myURL];
your property e
has the retain flag set. Therefore, after it retains it you've increased the retain count by two. You should release the object after handing it over to the property.
self.e = [[[NSMutableDictionary alloc] initWithContentsOfURL:myURL] autorelease];
精彩评论