Tuesday, February 7, 2023
Learning Code
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
Learning Code
No Result
View All Result
Home Swift

UIKit – loadView vs viewDidLoad

learningcode_x1mckf by learningcode_x1mckf
September 10, 2022
in Swift
0
UIKit – loadView vs viewDidLoad
74
SHARES
1.2k
VIEWS
Share on FacebookShare on Twitter


You might also like

The abstract Vapor service factory design pattern

SwiftNIO tutorial – The echo server

Introducing – Vapor cheatsheet – The.Swift.Dev.

Weak, unowned or robust subviews?


I’ve bought various emails and tweets about this matter, so I made a decision to put in writing about it, as a result of it’s actually arduous to discover a correct reply for this query on the web. There are some great posts and programming guides, some some articles are a bit older, nonetheless many individuals are asking the weak vs strong IBOutlet query even on the official forums, however noone actually explains the explanations, even on the forums they solely suggest this WWDC session video. So what is going on on right here? 🤔



I did a little analysis on the subject and the very very first thing that we should always state is that this: Apple removed the viewDidUnload method in iOS6 and from that model the iOS view controller lifecycle modified a bit. If you do not know a lot in regards to the lifecycle strategies (demystified), it is best to learn this article. This was fairly an enormous change and Apple additionally touched their inside view administration. Earlier than iOS6 it was a standard follow to outline weak subviews. As a result of that they had a robust reference to it and so they weren’t releasing it except you eliminated it from the view hierarchy.


This was about 10 years in the past. Now why are we nonetheless afraid of robust subviews? The primary cause was the addSubview methodology. The documentation states that it will create a robust reference, which robotically triggered my mind and I outlined my views as weak pointers, since they are going have a robust reference to their dad and mom. Appears cheap, proper? 🧠


Weak subviews


Properly, the issue is that if you wish to outline a weak variable we’ve to make use of an non-obligatory, however I do not like the thought of utilizing an non-obligatory variable for the reason that view goes to be at all times there, it is a part of the view hierarchy sooner or later in, it isn’t going anyplace. It is solely going to be “destroyed” when my view controller is deallocated. Ought to I declare it as an implicitly unwrapped non-obligatory?!? Possibly.



import UIKit

class ViewController: UIViewController 

    weak var foo: UILabel! 
    weak var bar: UILabel? 
    
    override func viewDidLoad() 
        tremendous.viewDidLoad()

        
        foo.removeFromSuperview()
        foo.textual content = "crash"
    


Truly you possibly can go flawed with unwrapped weak pointers, as a result of if you happen to take away your view from the view hiearchy sooner or later in time earlier than the view controller deallocation then your weak pointer shall be nil. On this case there will not be any extra robust references and your view shall be deallocated immediately, so if it is an implicitly unwrapped non-obligatory, then we’ve a hassle. Your app will crash if you happen to attempt to entry the property, as a result of it may have a nil worth.


So sure you need to use implicitly unwrapped non-obligatory variables to retailer subviews, however solely if you’re certain that you’re not going to take away it from the hiearchy. This additionally implies that you do not belief Apple’s view administration system, which is okay, there could be bugs, however truthfully that is fairly a vital characteristic and it has been round for a decade by now. 🙃


The opposite different is to make use of an everyday weak non-obligatory variable, however in that case you may at all times should test if it is nil or not, which goes to be a ache within the ass, however no less than you are going to be secure for certain. Private opinion: it will not definitely worth the effort in any respect and I by no means saved views like this.



Robust subviews


My advice is to belief Apple and outline your subviews as robust properties. Okay, this will also be problematic in case you have different robust references to the identical stuff, however normally if the view controller has the one reference to that given subview you ought to be completely tremendous.


Since it is a robust property you additionally should initialize the view, however that is not an enormous deal. You’ll be able to at all times initialize a view with a .zero body and that is it. Alternatively you possibly can create a subclass with an everyday init() methodology, that is even higher, becuase you’ll use auto layout for certain and this manner can set the translatesAutoresizingMaskIntoConstraints property in a single go.


import UIKit

class Label: UILabel 
    
    init() 
        tremendous.init(body: .zero)

        self.translatesAutoresizingMaskIntoConstraints = false
    
    
    @accessible(*, unavailable)
    required init?(coder: NSCoder) 
        fatalError("init(coder:) has not been carried out")
    
    
    deinit 
        print("deinit Label")
    


class ViewController: UIViewController 

    
    var foo: Label = .init()
    var bar: UILabel = .init(body: .zero)
    
    override func viewDidLoad() 
        tremendous.viewDidLoad()
        
    
    
    deinit 
        print("deinit ViewController")
    
    


By implementing a customized deinit methodology and even higher, by creating a symbolic breakpoint you possibly can simply detect retain cycles and repair reminiscence points. I made some assessments and I can verify you do not have to be afraid of robust views, each the viewcontroller and the view goes to be deallocated if it is wanted. 👻


Unowned subviews


Unowned and weak are more or less equivalent, I would say that you just will not have to outline views as unowned references, as a result of they are often problematic if it involves initialization. It is often higher to have a weak reference and test for nil values, however in fact there could be some circumstances the place you may want an unowned subview reference.


Utilizing loadView and viewDidLoad



The loadView methodology can be utilized to create your individual views manually. It is best to by no means name this methodology straight, but it surely’s save to override it. The opposite factor that you shouldn’t is that if you’re utilizing this methodology to override the foundation view, then you definitely should not name tremendous.loadView().



import UIKit

class ViewController: UIViewController 
    
    override func loadView() 
        view = UIView(body: .zero)

        
            
    


In each different case once you simply wish to add views to the view hierarchy, it is utterly tremendous to name the tremendous methodology. I am often implementing this methodology to setup views and constraints.


import UIKit 

class ViewController: UIViewController 

    var foo: Label = .init()
    
    override func loadView() 
        tremendous.loadView()
        
        view.addSubview(foo)
        
        NSLayoutConstraint.activate([
            view.centerXAnchor.constraint(equalTo: foo.centerXAnchor),
            view.leadingAnchor.constraint(equalTo: foo.leadingAnchor),
            view.trailingAnchor.constraint(equalTo: foo.trailingAnchor),
            foo.heightAnchor.constraint(equalToConstant: 44),
        ])
    


This manner I can make sure that each single view is prepared by the point the viewDidLoad methodology is named. It’s doable to configure views contained in the loadView methodology too, however I choose to maintain the hierarchy setup there and I place every little thing else contained in the viewDidLoad operate. I imply controller associated stuff solely, like establishing navigation bar buttons and issues like this.


As I discussed this in my previous article, I choose to make use of subclasses to configure my views, I additionally transfer structure constraints there (as a operate that returns them based mostly on some parameters) to maintain the view controller clear. Contained in the viewDidLoad methodology I can carry out extra consumer interface associated actions, however that is it I do not use it for including or styling views anymore.




Source link

Share30Tweet19
learningcode_x1mckf

learningcode_x1mckf

Recommended For You

The abstract Vapor service factory design pattern

by learningcode_x1mckf
February 1, 2023
0
The abstract Vapor service factory design pattern

I've written a number of articles about manufacturing unit design patterns on my weblog and this time I might like to speak a couple of particular one, which...

Read more

SwiftNIO tutorial – The echo server

by learningcode_x1mckf
January 27, 2023
0
SwiftNIO tutorial – The echo server

Intoducing SwiftNIO In the event you used a excessive degree net framework, corresponding to Vapor, up to now, you would possibly had some interplay with occasion loops...

Read more

Introducing – Vapor cheatsheet – The.Swift.Dev.

by learningcode_x1mckf
January 23, 2023
0
Introducing – Vapor cheatsheet – The.Swift.Dev.

Out there on Gumroad Thanks for supporting my work by buying the cheatsheet. 🙏 Download now A whole Vapor framework reference for novices. greater than...

Read more

iCloud Programming Tutorial for iOS: An Introduction

by learningcode_x1mckf
January 18, 2023
0
iCloud Programming Tutorial for iOS: An Introduction

Editor’s observe: This week, we work with Ziad Tamim once more to provide you an introduction of iCloud programming. You’ll learn to save and retrieve knowledge from iCloud.On...

Read more

Easy multipart file upload for Swift

by learningcode_x1mckf
January 18, 2023
0
Easy multipart file upload for Swift

I imagine that you've got already heard in regards to the well-known multipart-data add method that everybody likes to add recordsdata and submit type knowledge, but when not,...

Read more
Next Post
JavaScript had a hand in delivering James Webb Space Telescope’s images

JavaScript had a hand in delivering James Webb Space Telescope’s images

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Related News

Meet Bun: A JavaScript Runtime for the Whole Dev Lifecycle

Meet Bun: A JavaScript Runtime for the Whole Dev Lifecycle

September 23, 2022
JavaScript Typeof for Data Types: Array, Boolean and More

JavaScript Typeof for Data Types: Array, Boolean and More

January 20, 2023
Javascript Promises— Is There a Better Approach? | by Anisha Jain | Dec, 2022

Javascript Promises— Is There a Better Approach? | by Anisha Jain | Dec, 2022

December 8, 2022

Browse by Category

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

RECENT POSTS

  • C++ Is TIOBE's Language Of The Year – iProgrammer
  • JobRunr, the Java Scheduler Library, Released Version 6.0 – InfoQ.com
  • An Introduction to Lodash and Its Benefits for JavaScript Developers – MUO – MakeUseOf

CATEGORIES

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

© 2022 Copyright Learning Code

No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#

© 2022 Copyright Learning Code

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?