Is it necessary to use autoreleasepool in a Swift program?

前端 未结 2 527
说谎
说谎 2020-11-22 12:58

On page 17 of this WWDC14 presentation, it says

Working with Objective-C? Still have to manage autorelease pools
autoreleasepool { /* code */ }<

2条回答
  •  -上瘾入骨i
    2020-11-22 13:49

    If you would use it in the equivalent Objective-C code, then you would use it in Swift.

    will Swift be smart enough to know that the number variable should be released after the first }

    Only if Objective-C does. Both operate along the Cocoa memory management rules.

    Of course ARC knows that number goes out of scope at the end of that iteration of the loop, and if it retained it, it will release it there. However, that does not tell you whether the object was autoreleased, because -[NSNumber numberWithInt:] may or may not have returned an autoreleased instance. There is no way you can know, because you don't have access to the source of -[NSNumber numberWithInt:].

提交回复
热议问题