Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Any idea why this is error. #21

Open
mlch911 opened this issue Jan 16, 2024 · 2 comments
Open

Any idea why this is error. #21

mlch911 opened this issue Jan 16, 2024 · 2 comments

Comments

@mlch911
Copy link
Contributor

mlch911 commented Jan 16, 2024

This code get an error: Value of type '(UIView) -> () -> UIView' has no member 'window'

@AssociatedObject(.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
private var autoMaskView: UIView = {
    let view = UIView()
    view.bk_(whenTapped: { [weak self] in
        self?.window?.endEditing(true)
    })
    return view
}()

But after I replace the code with the macro expaned code, the error goes away.🤣

static var __associated_autoMaskViewKey: UInt8 = 0
private var autoMaskView: UIView
{
    get {
        if let value = objc_getAssociatedObject(
            self,
            &Self.__associated_autoMaskViewKey
        ) as? UIView {
            return value
        }
        let value = {
            let view = UIView()
            view.bk_(whenTapped: { [weak self] in
                self?.window?.endEditing(true)
            })
            return view
        }()
        objc_setAssociatedObject(
            self,
            &Self.__associated_autoMaskViewKey,
            value,
            .OBJC_ASSOCIATION_RETAIN_NONATOMIC
        )
        return value
    }
    set {
        objc_setAssociatedObject(
            self,
            &Self.__associated_autoMaskViewKey,
            newValue,
            .OBJC_ASSOCIATION_RETAIN_NONATOMIC
        )
    }
}
@p-x9
Copy link
Owner

p-x9 commented Jan 16, 2024

Regardless of Macro, it should not be possible to capture self before Self is initialized.

How about modifying it to assign after initialization as follows?

import UIKit

extension UIView {
    func bk_(whenTapped: () -> Void) {}
}

extension UIViewController {
    @AssociatedObject(.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    private var autoMaskView: UIView?

    func setup() {
        autoMaskView = { [self] in
            let ss = self
            let view = NSView()
            view.bk_(whenTapped: { [weak ss] in
                self?.window?.endEditing(true)
            })
            return view
        }()
    }
}

@mlch911
Copy link
Contributor Author

mlch911 commented Mar 28, 2024

So the Macro is build before Self is initialized. It's different from just using a computing property, right?

So if I want to capture self, I can't use @AssociatedObject.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants