Why do we need a temporary object?
As I have seen in many examples, first they allocate memory for the temporary object and later the same object is assigned to self. For example, I have a code snippet here :
-(void)viewDidLoad {
[super viewDidLoad];
Movie *newMovie = [[[Movie alloc] initWithTitle:@"Iron Man"
boxOfficeGross:[NSNumber numberWithFloat:650000000.00]
summary:@"Smart guy makes cool armor"] autorelease];
self.movie = newMovie;
}
Why cant we perform like:
self.movie =[[[Movie alloc] initWithTitle:@"Iron Man"
boxOfficeGross:[NSNumber numberWithFloat:6500000开发者_JS百科00.00]
summary:@"Smart guy makes cool armor"] autorelease];
Both are essentially the same. They adhere to the ownership clause – You release what create/retain. The difference, though not so obvious here, is that the time it takes for an autoreleased object to be released. Say, if loads of such autoreleased objects lingered around in the memory, this could create memory problems. If we released them and their retain count is zero, they are immediately deallocated and memory is freed up.
You don't need the temporary object. Your suggestion is perfectly valid.
However, if you need to set properties or call methods after creating the object, using a temporary object may be a little nicer than calling self.movie
multiple times:
Movie *newMovie = [[[Movie alloc] initWithTitle:@"Iron Man" boxOfficeGross:[NSNumber numberWithFloat:650000000.00] summary:@"Smart guy makes cool armor" ] autorelease];
newMovie.rating = 4;
[newMovie fetchImageFromServer];
self.movie = newMovie;
Personally, I do not use autorelease
in that scenario, but that's more a style preference:
Movie *newMovie = [[Movie alloc] initWithTitle:@"Iron Man" boxOfficeGross:[NSNumber numberWithFloat:650000000.00] summary:@"Smart guy makes cool armor" ];
newMovie.rating = 4;
[newMovie fetchImageFromServer];
self.movie = newMovie;
[newMovie release];
精彩评论