为什么我们需要一个临时对象? [英] Why do we need a temporary object?

查看:60
本文介绍了为什么我们需要一个临时对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如我在许多示例中看​​到的那样,首先它们为临时对象分配内存,然后将同一对象分配给self.例如,我在这里有一个代码段:

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

推荐答案

两者基本相同.他们遵守所有权条款–您释放创建/保留的内容.区别(尽管在这里不是很明显)是释放自动释放对象所花费的时间.说,如果这种自动释放对象的负载在内存中徘徊,则可能会导致内存问题.如果我们释放它们,并且它们的保留计数为零,那么它们将立即被释放并释放内存.

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.

这篇关于为什么我们需要一个临时对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆