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
相关产品推荐
相关产品推荐

