Why do people always use reassignment for instance variables in Objective-C (namely iPhone)? -


I always look at the example code where instead of saying in the viewDidLoad method, for example

  Some instancevar = [[classname alloc] init];  

They always

  class name * tempVar = [[classname alloc] init]; Some instanceVar = tempVar; [TempVar release];  

Why is that so? Is not this exactly the same thing, just now?

Short answer: This method is displayed in the iPhone code all the time Because it is considered the best way to create a new object and it is specified in the variable of a member, while still respecting all the memory management rules and proper side effects (if any) while avoiding the use of autorex also for.

Description:

Your second example would be zombie, because var has been left a pointer to memory Which has been released. One more likely use case looks like this:

  tempVar = [[classname alloc] init]; Self.propertyVar = tempVar; [TempVar release];  

Assuming that propertyVar is declared as property by copy or retention This code closes the ownership of the new object in the class.

Update 1: The following code is equivalent, but not recommended on iOS *, perhaps that is why most iPhone programs instead of the first pattern Use.

  self.propertyVar = [[[classname alloc] init] autorelease];  

* autorelease is on ios because the easiest way to make problems can be to use more because of it is a way to ensure that you do not overuse it Do not use it anytime, so that you will see the iOS code which uses alloc / init and release , even when autorelease acceptable. This is a matter of choice of code.

This 2G: pattern is being confused at first because because of memory management, the coco is automatically behind the scenes. To help describe all of this key member is the dot notation used to set the variable, assume that the following two lines of code are same :

  Self.propertyVar = value; [Self Setproperty Beat: Value];  

When you use dot notation, the coca indicator will use the property assessor for the member variable. If that property is defined as property copy or retention (and it is the only way to work without making zombie the only way of this method), then

  1. Any value that is first stored in propertyVar
  2. The new value is kept or copied < / Li>
  3. Any side effects (for example, KVC / KVO notifications) are automatically controlled Are

Comments