开发者

what's the difference between two code scenario

Scenario1:

NSDictionary *dictionary =
              [[NSDictionary alloc] initWithContentsOfFile:plistPath];
self.stateZips = dictionary;
[dictionary release];

Scenario2:

self.stateZips = [[NSDictionary alloc] initWithContentsOfFile:plistPath开发者_开发问答];


dependes on stateZips property.
If it is retained:
Scenario 1: stateZips is properly retained ( a release on stateZips will call its dealloc). also local dictionary is released then and there.
Scenario 2: stateZips is retained twice ( a release in stateZips will not call its dealloc as it is still retained).

If it is assigned:
Scenario 1: stateZips points to released dictionary and accessing it else where might result in crash.
Scenario 2: stateZips is properly retained ( a release on stateZips will call its dealloc).

copy is not being considered, as i believe its not your intention (at least in this piece of code)


Both cause self.stateZips to be set to a dictionary initialized with the file pointed to in plistPath.

But in the second, the pointer to the initialized dictionary was not saved, and as it's an object with a retain count of +1 technically a release message needs to be sent to it in some place, to balance the memory management. But as there is no way to retrieve the pointer to that object, you'll end up with a memory leak.

Two exceptions apply:

1.Garbage Collection
If you're in a garbage collected environment, both are the same. Well, they are not the same, but the result is similar.

2.Property type
If the setter for stateZips simply assigns the pointer, then you can release the object using the ivar pointer. Then these two pieces of code have only one difference: in the former, the object is released right after it's used. In the latter, it's just "undefined". Without the context, it's hard to determine if this object was released or not, and when.


I am assuming that stateZips is a property with the retain attribute.

In Scenario 1. A dictionary is created with a retain count of 1 in the first line. In the second line the property will call retain again, increasing the retain count to 2. Finally the retain count is decremented by the release. This will leave the dictionary with the correct retain count.

In Scenario 2, the retain is only called once.

The net effect of the two scenarios is the same. The dictionary object will be retained, and you will need to include a release in the dealloc method of the class.

If this were not correctly handled by the compiler, it would be very hard indeed following the retain/release rules of objective-c.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜