繁体   English   中英

对于视图 model 中的 swift 引用,自引用应该是弱的还是未知的?

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

我的所有功能都在我的观点 model 中将 self 引用为弱,但是我刚刚读到“如果捕获的引用永远不会变为 nil,它应该始终被捕获为无主引用,而不是弱引用。” 这是链接 这是我的代码的一些示例,显然我的观点 model 是 class,所有这些功能都在我的观点 model

(PS,其中一些代码很糟糕,我理解,我想在重构之前降低我的 memory 分配):

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
                        }
                        
                    }
                }
            }
        }
    }

真的很想确保我以尽可能最好的方式分配 memory 资源,并且被上面的引用所抛弃。 我错过了什么吗? model 视图中的最佳实践是什么? 最后,在闭包中我将 self 设置为可选,我应该强制解包吗? 是否存在从 memory 中释放视图 model 的情况?

任何有关该主题的知识都值得赞赏,真的很想把它记下来。

你说:

我……被上面的引述吓了一跳。 我错过了什么吗?

weak引用和无主引用的区别仅仅在于,当unowned被释放时,它将通过一个额外的步骤 go 和nil归还weak引用,而不是unowned引用。 因此,具有unowned引用的代码可能会更有效。 但是当你使用unowned时必须小心,因为如果你在 object 被释放后尝试使用该引用,应用程序将会崩溃。

model 视图中的最佳实践是什么?

就个人而言,我只会使用weak 开销并不重要,并且异步代码的存在使关于无主引用的推理以及unowned在到达unowned引用时是否被释放的推理变得非常复杂。

最后,在闭包中我将 self 设置为可选,我应该强制解包吗? 是否存在从 memory 中释放视图 model 的情况?

您绝对不想在处理异步代码时强制展开。 如果视图及其关联视图 model 在异步完成处理程序代码运行时被释放怎么办?! 如果你知道它永远不会是nil ,你应该只强制 unwrap (这里不是这种情况)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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