如何在ARC下正确管理这个UIBarButtonItem的内存?
我习惯了在以前版本的 iOS 中编程,对 iOS 5 和 ARC 还很陌生。
我有以下代码:
UIBarButtonItem *backbutton = [[UIBarButtonItem alloc] initWithTitle:@"Bill"
style:UIBarButtonItemStyleBordered
target:nil
action:nil];
self.navigationItem.backBarButtonItem = backbutton;
在以前的 iOS 版本中,我必须显式释放后退按钮。在 iOS 5 中我想知道这是如何完成的。这段代码位于视图控制器的“viewDidLoad”方法中。
I am used to programming in the previous versions of iOS, and new to iOS 5 and ARC.
I have the following piece of code:
UIBarButtonItem *backbutton = [[UIBarButtonItem alloc] initWithTitle:@"Bill"
style:UIBarButtonItemStyleBordered
target:nil
action:nil];
self.navigationItem.backBarButtonItem = backbutton;
In previous iOS versions I would have to explicitly release the back button. In iOS 5 I'm wondering how this is done. This piece of code is in the "viewDidLoad" method of a view controller.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于您使用的是 ARC,因此无需执行任何操作即可释放按钮。它将自动释放。 ARC 的诞生是为了让您无需释放所有内容。它将由 Xcode 编译器处理。
Because you are using ARC, you do not need to do anything to release the button. It will be released automatically. ARC was made to make it not necessary to release everything. It will be handled by the Xcode compiler.
在幕后,iOS 5 仍然使用保留计数来执行内存管理,并在不再引用对象时释放对象。在 ARC 之前,iOS 中的内存管理完全依赖程序员来覆盖所有运行时的可能性(悲惨)。其他环境(例如 .NET 和 OS X)会定期将未引用对象的保留计数设置为零。这种“垃圾收集”运行时系统会意外地减慢执行速度。 ARC 的独特之处在于 - 据我所知 - 它是第一个完全通过使用编译器对每个可能的执行路径进行静态分析来执行的内存管理解决方案(很棒)。
基本上,编译器会根据需要透明地插入
release
、retain
或autorelease
语句。理论上,由工厂方法(例如[NSString stringWithString]
)创建的对象与由[[NSString alloc] initWithString]
创建的对象具有相同的生命周期。有谁知道 LLVM 编译器是否以不同的方式对待分配的对象?Under the hood, iOS 5 still performs memory management using retain counts and releasing objects when they are no longer referenced. Before ARC, memory management in iOS relied exclusively on the programmer to cover all run-time possibilities (miserable). Other environments, like .NET and OS X, periodically set retain counts of unreferenced objects to zero. This run-time system of 'garbage collection' slows execution unpredictably. ARC is unique in that - as far as I know - it is the first solution to memory management that is performed entirely by static analysis of every possible execution path, using the compiler (wonderful).
Basically, the compiler transparently inserts
release
,retain
, orautorelease
statements as it sees fit. In theory, an object made by a factory method such as[NSString stringWithString]
will have the same life as an object created by[[NSString alloc] initWithString]
. Does anybody know if the LLVM compiler treats analloc
'ed object any differently?编辑是因为我错误地表示您可以在 ARC 下释放/保留。你不能。这是一个很好的解释:
有关 iOS5 SDK 中自动引用计数的一些问题
Edited because I was incorrect in saying that you could release/retain under ARC. You cannot. This is a good explanation:
Some questions about Automatic Reference Counting in iOS5 SDK