I am developing an iPhone app with ARC option enabled. i am creating IBOutlets in .h files which are connected from file owners icon to .xib elements.for eg.
IBOutlet UIButton *bt;
@property(nonatomic,retain)IBOutlet UIButton *bt;
in .m file, i am doing
@synthesize bt;
Is there a need to explicitly set bt
to nil in viewDidUnload
method? ie self.bt = nil;
in viewDidUnload
?
Also, do I need to write dealloc
method with ARC option enabled? When should I make IBOutlets elements as strong and weak references with ARC enabled?
There's a difference between the need to put your outlets to nil in viewDidUnload
and dealloc
Having ARC means you don't need to write that in your dealloc
method (it gets done automatically), however the viewDidUnload
method serves another purpose, and it is to free memory that the application isn't using when a memory warning occurs. dealloc
is still needed in some cases, for example, when your class is registered for a notification, or when your class is someone else's delegate and you don't want some glitchy callback giving you a bad access
When you get a memory warning, all the UIViewControllers
not being displayed will unload their view and call that method to free up memory. If you are still retaining outlets (like buttons, tables and etc) they will not get released, thus, killing the purpose of the viewDidUnload method.
When using ARC there is no need to use modifiers like retain
or copy
, for example. That kind of memory managment is done automatically using the strong
and weak
modifiers.
You also don't have to worry about writing dealloc
methods.
strong
is kind of the equivalent of retain
, so you should mark your outlets with it
@property(nonatomic, strong) IBOutlet UIButton *bt;
That's the way interface builder creates them by default.
I won't go into detail about their semantic differences, but you should really have a look at Apple's guide on transitioning to ARC if you want to know what's going on and read about the specifics of strong
and weak
modifiers.
EDIT: Sorry, interface builder creates outlets with weak
by default.
EDIT 2: strong
and retain
are indeed 100% identical. (thanks to @Adam)
EDIT 3: You set your pointers to nil
to avoid getting any message sent to deallocated instance
or BAD_ACCESS_EXCEPTION
errors.
If you are actually using ARC, you should make your outlets (nonatomic, weak)
instead of (nonatomic, strong)
. By using the weak
zeroing pointers, what the compiler does is automatically set your outlets to nil
when nothing else references them.
So, summing up, if you don't use weak
properties, you should set your pointers to nil.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.