Kiran Kulkarni
Kiran Kulkarni

Reputation: 1504

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:650000000.00]
                                  summary:@"Smart guy makes cool armor"] autorelease];

Upvotes: 4

Views: 157

Answers (3)

Deepak Danduprolu
Deepak Danduprolu

Reputation: 44633

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.

Upvotes: 3

Hollance
Hollance

Reputation: 2976

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];

Upvotes: 0

RedBlueThing
RedBlueThing

Reputation: 42532

You don't need the temporary object. Your suggestion is perfectly valid.

Upvotes: 2

Related Questions