美文网首页
使用自动释放池NSAutoreleasePool

使用自动释放池NSAutoreleasePool

作者: 林希品 | 来源:发表于2023-05-07 12:56 被阅读0次

使用自动释放池
NSAutoreleasePool负责释放在代码块中的自动释放对象。通常,它是被UIKit自动调用的。但是也有一些场景我们需要手动创建NSAutoreleasePools。
举个例子,如果你创建太多的临时对象在你的代码中,你会注意到你的内存用量会增加直到对象被释放掉。问题是内存只有在UIKit排空(drains)自动释放池的时候才能被释放,这意味着内存被占用的时间超过了需要。
好消息是你可以在你的@autoreleasepool段中创建临时对象来避免上述情况。代码如下所示。

NSArray *urls = <# An array of file URLs #>;

for(NSURL *url in urls) {

    @autoreleasepool {

        NSError *error;

        NSString *fileContents = [NSString stringWithContentsOfURL:url

encoding:NSUTF8StringEncoding error:&error];

        /* Process the string, creating and autoreleasing more objects. */

    }
}

在每次迭代之后会自动释放所有的对象。

你可以阅读更多关于NSAutoreleasePool的内容Apple’s official documentation.

原链接:https://www.jianshu.com/p/9bdc83fe3555

相关文章

网友评论

      本文标题:使用自动释放池NSAutoreleasePool

      本文链接:https://www.haomeiwen.com/subject/mywhsdtx.html