为什么我们需要一个临时对象?
正如我在许多示例中看到的那样,首先它们为临时对象分配内存,然后将同一对象分配给 self。例如,我这里有一个代码片段:
-(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;
}
为什么我们不能执行如下操作:
self.movie =[[[Movie alloc] initWithTitle:@"Iron Man"
boxOfficeGross:[NSNumber numberWithFloat:650000000.00]
summary:@"Smart guy makes cool armor"] autorelease];
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];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
两者本质上是相同的。他们遵守所有权条款——您释放创建/保留的内容。尽管这里不太明显,但区别在于释放自动释放对象所需的时间。比如说,如果此类自动释放对象的负载在内存中徘徊,则可能会产生内存问题。如果我们释放它们并且它们的保留计数为零,它们将立即被释放并释放内存。
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.
但是,如果您需要在创建对象后设置属性或调用方法,那么使用临时对象可能比多次调用
self.movie
好一点:就我个人而言,我不使用
autorelease
在这种情况下,但这更多的是一种风格偏好: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:Personally, I do not use
autorelease
in that scenario, but that's more a style preference: