简体   繁体   中英

For swift references within view model, should self reference be weak or unknown?

I have all my functions within my view model referencing self as weak, however I just read "If the captured reference will never become nil, it should always be captured as an unowned reference, rather than a weak reference." Here is link . Here is some examples of my code, obviously my view model is a class, all these functions are within my view model

(PS, some of this code is pretty bad I understand, I want to get my memory allocation down before I refactor):

func fetchUserProfilePhoto(completion: @escaping () -> Void) {
        let resource = GetUserProfilePhotoResource(userId: self.userId)
        let request = APIRequestSingle(resource: resource)
        self.userProfilePhotoRequest = request
        request.execute { [weak self] result in
            switch result {
            case .success(let value):
                self?.userProfile?.profilePhotoURL = value.photoUrl
                self?.fetchUserProfileImage()
            case .failure(let error):
                print("user profile image \(error)")
                switch error.resolveCategory() {
                case .nonRetryable:
                    self?.userProfilePhotoError = true
                    self?.retryableError = false
                case .retryable:
                    self?.userProfilePhotoError = true
                    self?.retryableError = true
                case .requiresLogout:
                    print("User profile photo LOGOUT")
                }
            case .none:
                print("Nothing from fetch User profile Photo")
            }
        }
    }

func postUserProfilePhoto(photo: UIImage) {
        guard !userProfilePhotoIsLoading else {return}
        userProfilePhotoIsLoading = true
        postProfilePhotoPresignedURL(numberOfImages: 1) { [weak self] url in
            for i in url {
                self?.putUserProfilePhoto(url: i.uploadURL, savedUrl: i.imageURL, profilePhoto: photo) { [weak self] in
                    self?.postUserProfilePhotoToAPI(photoUrl: i.imageURL) { [weak self] in
                        self?.fetchUserProfilePhoto() { [weak self] in
                            self?.userProfilePhotoIsLoading = false
                        }
                        
                    }
                }
            }
        }
    }

Really want to make sure I am allocating memory resources in the best possible fashion and was a little thrown off by the quote above. Am I missing something? What are best practices within the view model? Lastly, within the closure I am setting self to optional, should I force unwrap? Is there any case in which a view model would be deallocated from memory?

Any knowledge on the subject is appreciated, really want to get this down.

You said:

I … was a little thrown off by the quote above. Am I missing something?

The difference between weak and unowned is merely that when the object is deallocated, it will go through an extra step and go back and nil the weak references, but not the for unowned references. The code with unowned references can therefore be slightly more efficient. But one must be scrupulous about when you use unowned , as the app will crash if you try to use that reference after that object has been deallocated.

What are best practices within the view model?

Personally, I would just use weak . The overhead is immaterial and the presence of asynchronous code significantly complicates the reasoning about unowned references and whether the object be deallocated by the time one reaches the unowned reference.

Lastly, within the closure I am setting self to optional, should I force unwrap? Is there any case in which a view model would be deallocated from memory?

You absolutely do not want to force unwrap whenever dealing with asynchronous code. What if the view and its associated view model were deallocated by the time the asynchronous completion handler code runs?! You should only force unwrap if you know that it can never be nil (which is not the case here).

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM