Should IBOutlets be strong or weak under ARC?

125,655

Solution 1

The current recommended best practice from Apple is for IBOutlets to be strong unless weak is specifically needed to avoid a retain cycle. As Johannes mentioned above, this was commented on in the "Implementing UI Designs in Interface Builder" session from WWDC 2015 where an Apple Engineer said:

And the last option I want to point out is the storage type, which can either be strong or weak. In general you should make your outlet strong, especially if you are connecting an outlet to a subview or to a constraint that's not always going to be retained by the view hierarchy. The only time you really need to make an outlet weak is if you have a custom view that references something back up the view hierarchy and in general that's not recommended.

I asked about this on Twitter to an engineer on the IB team and he confirmed that strong should be the default and that the developer docs are being updated.

https://twitter.com/_danielhall/status/620716996326350848 https://twitter.com/_danielhall/status/620717252216623104

Solution 2

WARNING, OUTDATED ANSWER: this answer is not up to date as per WWDC 2015, for the correct answer refer to the accepted answer (Daniel Hall) above. This answer will stay for record.


Summarized from the developer library:

From a practical perspective, in iOS and OS X outlets should be defined as declared properties. Outlets should generally be weak, except for those from File’s Owner to top-level objects in a nib file (or, in iOS, a storyboard scene) which should be strong. Outlets that you create will therefore typically be weak by default, because:

  • Outlets that you create to, for example, subviews of a view controller’s view or a window controller’s window, are arbitrary references between objects that do not imply ownership.

  • The strong outlets are frequently specified by framework classes (for example, UIViewController’s view outlet, or NSWindowController’s window outlet).

    @property (weak) IBOutlet MyView *viewContainerSubview;
    @property (strong) IBOutlet MyOtherClass *topLevelObject;
    

Solution 3

While the documentation recommends using weak on properties for subviews, since iOS 6 it seems to be fine to use strong (the default ownership qualifier) instead. That's caused by the change in UIViewController that views are not unloaded anymore.

  • Before iOS 6, if you kept strong links to subviews of the controller's view around, if the view controller's main view got unloaded, those would hold onto the subviews as long as the view controller is around.
  • Since iOS 6, views are not unloaded anymore, but loaded once and then stick around as long as their controller is there. So strong properties won't matter. They also won't create strong reference cycles, since they point down the strong reference graph.

That said, I am torn between using

@property (nonatomic, weak) IBOutlet UIButton *button;

and

@property (nonatomic) IBOutlet UIButton *button;

in iOS 6 and after:

  • Using weak clearly states that the controller doesn't want ownership of the button.

  • But omitting weak doesn't hurt in iOS 6 without view unloading, and is shorter. Some may point out that is also faster, but I have yet to encounter an app that is too slow because of weak IBOutlets.

  • Not using weak may be perceived as an error.

Bottom line: Since iOS 6 we can't get this wrong anymore as long as we don't use view unloading. Time to party. ;)

Solution 4

I don't see any problem with that. Pre-ARC, I've always made my IBOutlets assign, as they're already retained by their superviews. If you make them weak, you shouldn't have to nil them out in viewDidUnload, as you point out.

One caveat: You can support iOS 4.x in an ARC project, but if you do, you can't use weak, so you'd have to make them assign, in which case you'd still want to nil the reference in viewDidUnload to avoid a dangling pointer. Here's an example of a dangling pointer bug I've experienced:

A UIViewController has a UITextField for zip code. It uses CLLocationManager to reverse geocode the user's location and set the zip code. Here's the delegate callback:

-(void)locationManager:(CLLocationManager *)manager
   didUpdateToLocation:(CLLocation *)newLocation
          fromLocation:(CLLocation *)oldLocation {
    Class geocoderClass = NSClassFromString(@"CLGeocoder");
    if (geocoderClass && IsEmpty(self.zip.text)) {
        id geocoder = [[geocoderClass alloc] init];
        [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
            if (self.zip && IsEmpty(self.zip.text)) {
                self.zip.text = [[placemarks objectAtIndex:0] postalCode];
            }
        }];    
    }
    [self.locationManager stopUpdatingLocation];
}

I found that if I dismissed this view at the right time and didn't nil self.zip in viewDidUnload, the delegate callback could throw a bad access exception on self.zip.text.

Solution 5

IBOutlet should be strong, for performance reason. See Storyboard Reference, Strong IBOutlet, Scene Dock in iOS 9

As explained in this paragraph, the outlets to subviews of the view controller’s view can be weak, because these subviews are already owned by the top-level object of the nib file. However, when an Outlet is defined as a weak pointer and the pointer is set, ARC calls the runtime function:

id objc_storeWeak(id *object, id value);

This adds the pointer (object) to a table using the object value as a key. This table is referred to as the weak table. ARC uses this table to store all the weak pointers of your application. Now, when the object value is deallocated, ARC will iterate over the weak table and set the weak reference to nil. Alternatively, ARC can call:

void objc_destroyWeak(id * object)

Then, the object is unregistered and objc_destroyWeak calls again:

objc_storeWeak(id *object, nil)

This book-keeping associated with a weak reference can take 2–3 times longer over the release of a strong reference. So, a weak reference introduces an overhead for the runtime that you can avoid by simply defining outlets as strong.

As of Xcode 7, it suggests strong

If you watch WWDC 2015 session 407 Implementing UI Designs in Interface Builder, it suggests (transcript from http://asciiwwdc.com/2015/sessions/407)

And the last option I want to point out is the storage type, which can either be strong or weak.

In general you should make your outlet strong, especially if you are connecting an outlet to a sub view or to a constraint that's not always going to be retained by the view hierarchy.

The only time you really need to make an outlet weak is if you have a custom view that references something back up the view hierarchy and in general that's not recommended.

So I'm going to choose strong and I will click connect which will generate my outlet.

Share:
125,655
hypercrypt
Author by

hypercrypt

Updated on November 24, 2020

Comments

  • hypercrypt
    hypercrypt over 3 years

    I am developing exclusively for iOS 5 using ARC. Should IBOutlets to UIViews (and subclasses) be strong or weak?

    The following:

    @property (nonatomic, weak) IBOutlet UIButton *button;
    

    Would get rid of all of this:

    - (void)viewDidUnload
    {
        // ...
        self.button = nil;
        // ...
    }
    

    Are there any problems doing this? The templates are using strong as are the automatically generated properties created when connecting directly to the header from the 'Interface Builder' editor, but why? The UIViewController already has a strong reference to its view which retains its subviews.

  • bearMountain
    bearMountain over 12 years
    How did you get the "developer library" link to jump to the particular part of the apple doc page? Whenever I link to the apple docs it always links to the top of the page (even if the content of interest is halfway down the page). Thanks.
  • Alexsander Akers
    Alexsander Akers over 12 years
    I copied the link from the navigation pane on the left. :D
  • Yang Meyer
    Yang Meyer over 12 years
    It is also my understanding that weak properties do not need to be nilled in viewDidUnload. But why does Apple’s template for creating outlets include a [self setMySubview:nil]?
  • Van Du Tran
    Van Du Tran about 12 years
    What does "except for those from File’s Owner to top-level objects in a nib file (or, in iOS, a storyboard scene)" mean?
  • mattjgalloway
    mattjgalloway about 12 years
    @VanDuTran - it means objects in the NIB that are at the root level, i.e. say you instantiated another view in there which isn't directly a subview of the main view, then it needs to have a strong reference.
  • cortices
    cortices about 12 years
    Yes, but you haven't directly answered the question.
  • jowie
    jowie almost 12 years
    If that is the case, then why is it when you choose "weak" from the drag-and-drop Referencing Outlets, Xcode automatically fills it in as "unsafe_unretained"? Which is correct?
  • David H
    David H almost 12 years
    Top level means that when you look at the nib, the object appears in the list on the left. Almost all nibs have a UIView in them - this might be the only top level object. If you add other items, and they show in the list, they are "top level objects"
  • user4951
    user4951 almost 12 years
    So we still need to do topLevelObject=nil at viewDidUnload? Otherwise none of those subclasses will be deallocated then given that topLevelObject still have references to all of them.
  • Dafydd Williams
    Dafydd Williams almost 12 years
    It explains it as at 2009. With ARC, this has changed significantly.
  • Dafydd Williams
    Dafydd Williams almost 12 years
    @jowie unsafe_unretained is what it'll produce if your project targets a version of iOS that's older than 5, but still supports ARC. If it targets only 5 or up, it'll give you weak instead.
  • Brett
    Brett almost 11 years
    @JimThio, I want to know the answer to your question too. Should we set the strong topLevelObject to nil on viewDidUnload?
  • Enzo Tran
    Enzo Tran almost 11 years
    Is there any real world cases where using strong/retained for your IBOutlet could cause problem? Or is it just a redundant retain, which means bad coding style but wouldn't affect your code?
  • Enzo Tran
    Enzo Tran almost 11 years
    Is there any real world cases where using strong/retained for your IBOutlet could cause problem? Or is it just a redundant retain, which means bad coding style but wouldn't affect your code?
  • Jingjie Zhan
    Jingjie Zhan almost 11 years
    @EnzoTran, if you set the IBOutlet to be strong(same as retain), then your outlets will have a second owner (the viewcontroller) other than the view that retained it already. So you have to release the memory used by that outlet in viewcontroller's viewDidUnload.
  • Enzo Tran
    Enzo Tran over 10 years
    @Jingjie Zhan: true, except that viewDidUnload is no longer called since iOS 6.
  • Just a coder
    Just a coder over 10 years
    @AlexsanderAkers hi, i know you did a good job explaining this.. but could you help me with this related question? I understand diagrams better than words --> stackoverflow.com/questions/18969138/…
  • hypercrypt
    hypercrypt over 10 years
    That is true, but you may still want to unload the view yourself. In which case you'd have to set all of your outlets to nil manually.
  • hypercrypt
    hypercrypt over 10 years
    PS: weak is a quite a bit cheaper in ARM64 :D
  • Tammo Freese
    Tammo Freese over 10 years
    That's right, if you implement view unloading, weak properties or __weak instance variables are the way to go. I just wanted to point out that there is less potential for error here. As for weak being cheaper on arm64, I have not even seen a real-life performance problem with weak IBOutlets on armv7. :)
  • karlbecker_com
    karlbecker_com about 10 years
    Is there such a thing as a redundant retain? If there's an extra retain, that will cause it to not be counted properly, and therefore won't be freed as soon as it could be since there's an extra retain on its retain count.
  • hypercrypt
    hypercrypt about 10 years
    Why not copy as it is an NSArray?
  • Tammo Freese
    Tammo Freese about 10 years
    In that case, strong makes sense as well. strong is only harmful if you use view unloading—but who does these days? :)
  • Motti Shneor
    Motti Shneor over 9 years
    :( the Big Nerd Ranch link is dead… yet I really need to read it. Anyone knows more details about that post, so I can find it?
  • Sergey Grischyov
    Sergey Grischyov over 9 years
    @MottiShneor don't worry, it's no big deal since the link was about times before ARC and is not relevant anymore.
  • Brody Robertson
    Brody Robertson over 9 years
    Good article on NSHipster on the topic: nshipster.com/ibaction-iboutlet-iboutletcollection
  • FreeNickname
    FreeNickname almost 9 years
  • Tammo Freese
    Tammo Freese almost 9 years
    @FreeNickname See my answer there. It's not a problem since gesture recognizers don't keep strong references to targets/delegates. :)
  • sunnyxx
    sunnyxx almost 9 years
    Top level object of view controller in storyboard will be stored in an array: _topLevelObjectsToKeepAliveFromStoryboard, but not for xib file, so top level objects' outlets could be weak if you're using storyboard.
  • hypercrypt
    hypercrypt almost 9 years
    Interesting. I guess this changed when view unloading was removed?
  • Daniel Hall
    Daniel Hall almost 9 years
    This looks like it is no longer true and the docs are in the process of being updated. - twitter.com/_danielhall/status/620716996326350848 - twitter.com/_danielhall/status/620717252216623104
  • Arunabh Das
    Arunabh Das over 8 years
    Is this really true or is the answer with 300+ upvotes the correct one? I noticed that InterfaceBuilder by default uses weak when you Ctrl-drag from the storyboard to the .h
  • kjam
    kjam about 8 years
    The one with 400+ votes is correct, but outdated. Since iOS 6 viewDidUnload doesn't get called, so there are no benefits for having weak outlets.
  • Cameron Lowell Palmer
    Cameron Lowell Palmer about 8 years
    @kjam there are benefits. First and foremost you shouldn't hold a strong reference to something you didn't create. Second, the performance gain is negligible. Don't violate best practices in programming simply because some guy, even a well placed guy, said this is 10 microseconds faster. Code clear intent, don't try to play optimizing compiler. Only code for performance when it has been measured in a specific case to be a problem.
  • kjam
    kjam about 8 years
    Let me disagree with you. 'Holding a strong reference to something you didn't create' happens all the time in Objective-C. That's why there is a reference counting, rather then a single owner. Do you have any references to back-up this recommendation? Could you pls list the other benefits of weak outlets?
  • GeneCode
    GeneCode over 7 years
    Why would you want to use viewUnloading?
  • Tammo Freese
    Tammo Freese over 7 years
    @Rocotilos The first iPhone had very limited RAM. If I recall correctly, 128 MB, leaving around 10 MB for the active app. Having a small memory footprint was crucial, hence there was view unloading. That changed as we now have more and more RAM, and Apple optimized UIViews in iOS 6, so that on memory warnings, a lot of memory can be freed without unloading the view.
  • petrsyn
    petrsyn over 7 years
    Here is the WWDC video mentioned in the answer developer.apple.com/videos/play/wwdc2015/407/?time=1946
  • micnguyen
    micnguyen about 7 years
    Great answer that explains the actual reason -why-
  • Chris Hanson
    Chris Hanson about 7 years
    “Is this really true or is the answer with [more] upvotes the correct one?” isn’t really a valid question, when this answer cites an Apple engineer as its source. You can consider what Apple says about Apple’s API usage to be correct by definition.
  • thibaut noah
    thibaut noah almost 7 years
    That is good and all but i have seen leaks coming from gesture recognizers implemented in storyboard.
  • McCygnus
    McCygnus about 6 years
    @ChrisHanson Almost 3 years later Apple's docs still state that they should be weak though "except for those from File’s Owner to top-level objects". So do we trust the docs or the engineer?
  • Malcolm
    Malcolm almost 6 years
    This answer just says "do this" and doesn't explain anything. If I need weak references sometimes, and at other times it doesn't matter, why would I ever use strong references? I don't care who posts this information, it has to be explained, otherwise it is just someone's opinion.
  • nickdnk
    nickdnk over 5 years
    It's odd that Ctrl-dragging to .h files still creates weak (as of XCode 10) if this is not recommended. I have no issues with this though. Everything works. It's quite confusing.
  • Amber K
    Amber K over 5 years
    I disagree that. The IBOutlets should be declared weak. Creating strong references wont allow views to deallocate. Its a good practice but can be a personal preference for those who know what they are doing. Eg create a strong reference to a nested subview in controller and removing its parent view would not deallocate the memory because its strong. Even better make outlets optional instead of implicitly unwrapped to avoid crashes.
  • user1872384
    user1872384 over 5 years
    I can't understand this line. "The only time you really need to make an outlet weak is if you have a custom view that references something back up the view hierarchy and in general that's not recommended." Any examples?
  • subin272
    subin272 about 5 years
    I have been checking on this issue for sometime and haven't found any concrete answers. Since the above link suggests that both are fine and in general go with what Xcode autosuggests.
  • touti
    touti almost 5 years
    I calculated the deinit time that weak and strong takes , and it's exactly the same.
  • thesummersign
    thesummersign almost 5 years
    But in swift this is more the case. Weak references are faster.
  • visc
    visc over 4 years
    @thesummersign I don't see a difference when I time weak for strong in swift..
  • ChuckZHB
    ChuckZHB over 3 years
    So who is correct? Xcode 12 use weak as default option when creating IBOutlets.