Objects not initialized
in objective C, I can do the following
UIImage *myImage = [UIImage imageNamed:@"myPhoto.jpg"];
variable.image = myImage;
and this works just fine. but the obje开发者_JS百科ct named "myImage" was never initialized, and the UIImage never had any memory allocated and yet the code still works..
Can someone explain what's going on here?
Yes, the object was initialised. The imageNamed:
method allocates and initialises an object, sends it an autorelease
message, then returns the memory address to you. You store that memory address in the pointer called myImage
.
myImage
and the object are two different things. myImage
merely points at a memory location. It is not the object itself.
You can pass around objects without assigning them to variables, and you can assign one object to many variables.
Consider this:
UIImage *imageOne;
UIImage *imageTwo;
imageOne = [UIImage imageNamed:@"myPhoto.jpg"];
imageTwo = imageOne;
The image wasn't copied. There is only one object in existence. Both variables point to it.
Now consider this:
NSLog(@"%@", [UIImage imageNamed:@"myPhoto.jpg"]);
You didn't assign it to any variable. But the object still existed, right?
Have a look in the documentation for UIImage
. Under the heading "Cached Image Loading Routines" and "Creating New Images" are some methods with a +
where you might expect a -
. This means that calling these methods is the same as calling [[[UIImage alloc] init] autorelease];
, though some of them do more (as in custom initialization).
Lots of other Objective C objects have similar methods, for example, NSArray
has a method +(id)array
that creates and returns an empty array. Your main indicator here is the +
instead of the -
, but I always check the documentation to check how the initialization is handled and to make sure the object is autoreleased.
精彩评论