Using Properties in Objective-C Tutorial
I’ll list the rules out first, and then we’ll have a discussion of each one.
- Always make a property for every instance variable.
- If it’s a class, mark it with the retain attribute. Otherwise, mark it with the assign attribute.
- Whenever creating a variable, use the alloc/init/autorelease idiom.
- Whenever setting a variable, always use “self.xxx = yyy” (in other words, use the property).
- For each of your instance variables, call “self.xxx = nil” in dealloc. If it’s an outlet or something you created in viewDidLoad, do the same in viewDidUnload.
Ok, now onto the discussion!
For rule #1: By making an instance variable for each property, you can let the compiler write the memory management code for you. The drawback is it doesn’t keep the private data of your class well encapsulated so can lead to more connected code if you are not careful.
For rule #2: By retaining variables whenever they are set, you can make sure that you can access your instance variables at any time.
For rule #3: When you create a variable, you want to use the alloc/init/autorelease idiom (like you can see creating the NSArray with the sushiTypes earlier). This way, the memory will be freed up for you automatically later on. If you need to keep the variable around long-term, you should assign it to a property, put it in an array, or the like to increment the reference count.
For rule #4: By using the self.xxx syntax (i.e. using the property) whenever you set a variable, you’ll go through the properties and hence make sure to release the old variable/retain the new variable. Note some programmers worry about using getters/setters/properties in initializers and dealloc, but I don’t think it’s something to worry about if you wrote & understand the code.
For rule #5: Calling “self.xxx = nil” will go through your properties and decrement the reference count. Don’t forget about viewDidUnload!
继续修炼,屌丝总有出头日