PeterK
PeterK

Reputation: 4301

NSDictionary, why is this

I am learning this trade and is currently focusing on NSDictionary. I am currently doing examples from the book "Beginning iPhone Development Exploring the iPhone SDK" (Dave Mark / jeff LaMarche).

The example i am working on is in chapter 7 (page 166), Tab Bars and Pickers.

I would like to ask why they use Dictionaries the way they do.

Here is the scenario:

in the .h file:

NSDictionary *stateZips;

The the .m file (viewDidLoad) they have the following code:

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

My question is if there is any specific Objective-C reason why they copy the dictionary to stateZips and not use stateZips to init from the plist to avoid the extra code? ...or if this is just the writers own way of doing things?

Upvotes: 2

Views: 268

Answers (2)

Jay Haase
Jay Haase

Reputation: 1989

Does the .m file also have a @synthesize statement for stateZips? I am guessing it has, because of the style of the allocation.

If there is a property declaration with retain, and a @synthesize statement for stateZips and you do this:

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

You will have a memory leak. The dictionary created in the statement above will have a retain count of 2 after the statement. One retain for the alloc, and one retain performed by the synthesized setter.

This is a side affect of using setters that contain retain statements, but if you do not use setters with retain statements you will probably have a lot bigger memory management problems... ;-)

To best understand these things you should study the use of @property's assign and retain and the code behind the synthesized setters and getters.

Upvotes: 2

CiNN
CiNN

Reputation: 9870

because I think stateZips is a property which retain.
So when they alloc/initWithContentsOfFile dictionary they need to release it since self.stateZips already retains it.

Upvotes: 0

Related Questions