gpt4 book ai didi

objective-c - 使用@autoreleasepools 的正确方法?

转载 作者:太空狗 更新时间:2023-10-30 03:58:22 25 4
gpt4 key购买 nike

我想知道下面的代码是否是使用新的 @autoreleasepool 的好方法,我应该这样使用它还是让主要的 autoreleasepool 处理对象?

  • (void) 调用 AutoReleasedObject,可能是我的 viewDidAppear 或类似函数。

谢谢!

- (UIBarButtonItem*)backButton {
UIBarButtonItem* backButton = [[UIBarButtonItem alloc] initWithTitle:@"CustomBackTitle"
style:UIBarButtonItemStyleBordered
target:nil
action:nil];
return [backButton autorelease];
}

- (void) callingAutoReleasedObject {

@autoreleasepool {
[[self navigationItem] setBackBarButtonItem:[self backButton]];
}
}

最佳答案

来自 Apple 的 reference :

There are, however, three occasions when you might use your ownautorelease pools:

  • If you are writing a program that is not based on a UI framework, suchas a command-line tool.

  • If you write a loop that creates manytemporary objects. You may create an autorelease pool inside the loopto dispose of those objects before the next iteration. Using anautorelease pool in the loop helps to reduce the maximum memoryfootprint of the application.

  • If you spawn a secondary thread. You must create your own autoreleasepool as soon as the thread begins executing; otherwise, yourapplication will leak objects. (See “Autorelease Pools and Threads”for details.)

我个人创建了几个 @autoreleasepool block 以避免严重的内存泄漏,在使用 Core Data 进行后台同步期间,因为框架(我喜欢它)创建了大量的自动释放对象,必须耗尽这些对象以保留可用内存; )

关于objective-c - 使用@autoreleasepools 的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9077172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com