Question

I have the following code:

NSDictionary *dict = @{ @"myKey" : @"myValue" };  

Should I release dict using release or autorelease?
Or I do not own the object, so I should not release it myself?

Note: I use manual reference counting (ARC is disabled).

Was it helpful?

Solution

No, you must not release a NSDictionary created with the literal syntax. The Clang documentation tells that dictionary literal expressions expand to +[NSDictionary dictionaryWithObjects:forKeys:count:], so you do not own the object.

No Objective-C literal expands to an expression creating an owning reference.

OTHER TIPS

Even if you have ARC disabled (which you should have it enabled), you do not need to release it because you do not own the object. You only own the object when you created it through alloc or new.

I asked the question too early, sorry. But here's the answer:

I tried analyzing it myself, since I cannot find references (maybe because of the vague keyword @{}).

When adding autorelease to the dictionary created by @{ @"myKey" : @"myValue" }, the app crashes. I also ran the code through Xcode's Static Analyzer, and it gave a Memory issue.
So, we do not need to release objects retrieved using @{}, similar to NSString from @"".

I also tried it for NSArray using @[]. The same behavior applies.
We do not need to release them ourselves.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top