问题描述
此WWDC14演示文稿的第17页,它说
那是什么意思?这是否意味着如果我的代码库中没有任何Objective-C文件,则autoreleasepool {}
是不必要的吗?
What does that mean? Does it mean that if my code base doesn't have any Objective-C files, autoreleasepool {}
is unnecessary?
在相关问题的答案中,有一个示例autoreleasepool
可能有用:
In an answer of a related question, there is an example where autoreleasepool
can be useful:
- (void)useALoadOfNumbers {
for (int j = 0; j < 10000; ++j) {
@autoreleasepool {
for (int i = 0; i < 10000; ++i) {
NSNumber *number = [NSNumber numberWithInt:(i+j)];
NSLog(@"number = %p", number);
}
}
}
}
如果上面的代码在删除了autoreleasepool
的情况下转换为Swift,Swift是否足够聪明,知道number
变量应该在第一个}
之后释放(就像某些其他语言一样)?
If the code above gets translated into Swift with autoreleasepool
dropped, will Swift be smart enough to know that the number
variable should be released after the first }
(like some other languages does)?
推荐答案
在返回autorelease
对象(通过Objective-C代码或使用Cocoa类创建)时,在Swift中使用autoreleasepool
模式. Swift函数中的autorelease
模式与Objective-C中的模式非常相似.例如,考虑此方法的Swift演绎(实例化NSImage
/UIImage
对象):
The autoreleasepool
pattern is used in Swift when returning autorelease
objects (created by either your Objective-C code or using Cocoa classes). The autorelease
pattern in Swift functions much like it does in Objective-C. For example, consider this Swift rendition of your method (instantiating NSImage
/UIImage
objects):
func useManyImages() {
let filename = pathForResourceInBundle
for _ in 0 ..< 5 {
autoreleasepool {
for _ in 0 ..< 1000 {
let image = NSImage(contentsOfFile: filename)
}
}
}
}
如果您在Instruments中运行此代码,则会看到如下所示的分配图:
If you run this in Instruments, you'll see an allocations graph like the following:
但是,如果在没有自动释放池的情况下执行此操作,则会看到峰值内存使用率更高:
But if you do it without the autorelease pool, you'll see that peak memory usage is higher:
autoreleasepool
允许您明确管理在Swift中释放自动释放对象的时间,就像在Objective-C中一样.
The autoreleasepool
allows you to explicitly manage when autorelease objects are deallocated in Swift, just like you were able to in Objective-C.
注意:处理Swift本机对象时,通常不会收到自动释放对象.这就是为什么演示文稿中提到了仅在使用Objective-C工作时"才需要的警告,尽管我希望Apple在这一点上更加清楚.但是,如果要处理Objective-C对象(包括Cocoa类),则它们可能是自动释放对象,在这种情况下,Objective-C @autoreleasepool
模式的这种Swift表示法仍然有用.
Note: When dealing with Swift native objects, you generally will not receive autorelease objects. This is why the presentation mentioned the caveat about only needing this when "working with Objective-C", though I wish Apple was more clear on this point. But if you're dealing with Objective-C objects (including Cocoa classes), they may be autorelease objects, in which case this Swift rendition of the Objective-C @autoreleasepool
pattern is still useful.
这篇关于在Swift程序中是否需要使用autoreleasepool?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!