You're confusing declaring variables with allocating memory/objects. The important part of your code in both cases above is actually this:
[UIImage imageNamed:@"image.png"];
This code happens to invoke a class method on the UIImage class that does a number of things. One of these things is an allocation and initialization of a UIImage object. In your first example you stored this allocated object into a variable called myImage
. You then moved your shiny new object into another (class) variable, `imageView.image'.
UIImage *myImage = ...
In the second example you gave you are still storing this allocated object in a variable, except that in this case you skipped the intermediary assignment and stored the object directly into the class variable imageView.image
.
imageView.image = [UIImage imageNamed:@"image.png"];
One way to think of variables vs objects is to compare them to houses. In this scenario a variable is your address, and the object is your house. Several people can have your address, but no matter how many they are, when they choose to visit, they are going to the same house. So in your examples myImage
and imageView.image
are addresses pointing to the same house, or object, an instance of UIImage. In your example you don't actually need to create the intermediary variable unless you are using it for some other purpose.
As far as the crashes, you should read up on Apple's memory management guide. It may take awhile but you will get used to the standards that Apple follows with respect to retaining and releasing objects. Note that the new Automatic Reference Counting in XCode 4.2
alleviates alot of these problems but it also has its own learning curve. But to summarize, you are getting crashes because you are releasing an object you do not own. The class method imageNamed
on UIImage returns an auto-released instance of that class. You do not need to send it another release in your code, and that is the likely source of your program crashes.