Why do we need a temporary facility?

As I saw in many examples, they first allocate memory for a temporary object, and then the same object is assigned to itself. For example, I have a piece of code:

-(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 can't we work like this:

 self.movie =[[[Movie alloc] initWithTitle:@"Iron Man" boxOfficeGross:[NSNumber numberWithFloat:650000000.00] summary:@"Smart guy makes cool armor"] autorelease]; 
+4
source share
3 answers

Both are essentially the same. They adhere to the terms of ownership - you let go of what you create / save. The difference, although not so obvious here, is that the time it takes to free an autorealized object. Say, if a lot of such auto-realized objects have accumulated in memory, this can create memory problems. If we released them, and their retention amount is zero, they are immediately freed and memory is freed.

+3
source

You do not need a temporary object. Your suggestion is absolutely correct.

+2
source

However, if you need to set the properties or methods of the call after creating the object, using a temporary object can be a bit nicer than calling self.movie several 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 this scenario, but this is 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]; 
0
source

All Articles