You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xcode中NSAutoreleasePool报错:ARC模式下不可用,求最新写法

解决Xcode中NSAutoreleasePool在ARC模式下的报错问题

嗨,我来帮你搞定这个报错!你遇到的问题是因为当前Xcode项目默认启用了Automatic Reference Counting (ARC)(自动引用计数)模式,而NSAutoreleasePool这个类在ARC环境下已经被废弃了——苹果早就提供了更简洁高效的替代语法:@autoreleasepool代码块。

你原来的报错代码:

{ 
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 
    NSLog(@"Base class Person Object"); 
    Person *person = [[Person alloc]initWithName:@"Raj" andAge:5]; 
    [person print]; 
    NSLog(@"Inherited Class Employee Object"); 
    Employee *employee = [[Employee alloc]initWithName:@"Raj" andAge:5 andEducation:@"MBA"]; 
    [employee print]; 
    [pool drain]; 
}

修改后的正确代码(ARC模式下):

@autoreleasepool {
    NSLog(@"Base class Person Object"); 
    Person *person = [[Person alloc] initWithName:@"Raj" andAge:5]; 
    [person print]; 
    NSLog(@"Inherited Class Employee Object"); 
    Employee *employee = [[Employee alloc] initWithName:@"Raj" andAge:5 andEducation:@"MBA"]; 
    [employee print];
}

关键说明:

  • 在ARC模式下,你不需要手动创建和释放NSAutoreleasePool实例,@autoreleasepool块会自动处理池的创建与销毁
  • 当代码执行到@autoreleasepool块结束时,池会自动被drain,块内的自动释放对象会被正确管理
  • 这种写法不仅更符合现代Objective-C的规范,也能避免手动管理内存带来的潜在问题

内容的提问来源于stack exchange,提问作者Nitin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:45:57