Search code examples
iosobjective-ciboutlet

Why some Outlets are made strong references even tough the documentation specifies that outlets should be weak reference


Hi I am a newbie to iOS programming. I know what a strong and weak reference is. But I get confused which type of reference to use when I have to deal with outlets. After going through the documentation which states that

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.

So what I understood after going through the above statement is that the Outlets that we create should typically be weak by default.

But while studying some tutorials I have come across the code where people have declared an outlet as strong reference. For example consider the following code :

@interface AboutViewController : UIViewController

@property (nonatomic, strong) IBOutlet UIWebView *webView;

@end

The code :

@property (nonatomic, strong) IBOutlet UIWebView *webView;

says that our AboutViewController has an UIWebView object.

But why we need a strong reference here for the UIView object?? As the document states shouldn't this be an weak reference ?

Also please explain in the documentation statement which I have quoted above what does the File’s Owner to top-level objects mean?.

I have gone through many of the similar questions on this website but none of them helped me to clear my doubt. So please help. Thanks in advance :)


Solution

  • What to use for non top level GUI elements - strong or weak - depends on how you are going to use their outlets. If you have a weak reference

    @property (nonatomic, weak) IBOutlet UIWebView *webView;
    

    then after calling method

    [webView removeFromSupeview];
    

    your webView will be nil and it will be impossible to restore UIWebView just by adding

    [self.view addSubview:webView];
    

    If this is appropriate for you - it is better to use weak because you will free webView's memory when you do not need it.

    On the other hand, in case of a strong reference after

    [webView removeFromSupeview];
    

    webView will still have referenceCount > 0 and webView will be deallocated only if owner will free it explicitly

    self.webView = nil;
    

    or in the owner's

    - (void)dealloc
    

    together with the owner itself.

    Usually there is no difference if you have static GUI. If you want to remove (not hide) some views add be able to add them later - strong references should be used.

    Top level objects should be retained strong. Like

    @property(nonatomic,retain) UIView *view;
    

    in UIViewController.