gpt4 book ai didi

objective-c - Objective-C - ARC、内存管理和 performSelectorInBackground?

转载 作者:搜寻专家 更新时间:2023-10-30 20:17:19 24 4
gpt4 key购买 nike

ARC 是否不再需要在后台线程中调用的方法上使用 @autoreleasepool?除非 doStuff 用@autorelease 池包装,否则以下代码假设会导致内存泄漏,但是当我运行仪器时,它显示用户已分配并在运行循环结束时被释放。

- (IBAction)buttonClicked:(id)sender {
[self performSelectorInBackground:@selector(doStuff) withObject:nil];
}

- (void)doStuff {
User *user = [[User alloc] init];
NSLog(@"%@", user);
}

最佳答案

虽然在 NSThread 的实现中可能暗示存在一个自动释放池,但文档中没有这样的保证。相反,文档明确指出:

performSelectorInBackground:withObject:

The method represented by aSelector must set up the thread environment just as you would for any other new thread in your program.

Threading Programming Guide

If your application uses the managed memory model [MRC and ARC, as opposed to Garbage Collection], creating an autorelease pool should be the first thing you do in your thread entry routine.

结论:虽然在某些特定情况下可能存在自动释放池,但不建议依赖这一事实。这是未记录的行为,可能会随着操作系统的每次发布或其他情况而改变。通常应避免在运输代码中使用。

关于objective-c - Objective-C - ARC、内存管理和 performSelectorInBackground?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25256255/

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