How do I access my Application Delegate's window accessor method from another object?

折月煮酒 提交于 2019-12-02 22:20:19
Ole Begemann

You can access the app delegate through the singleton UIApplication instance:

[[[UIApplication sharedApplication] delegate] window];

This is a special case, though, because you can access an object (the UIApplication instance) whose delegate you know is the object you want to access. The general case:

Expanding this a little, how does one access methods in other target objects that are not scope descendants of the object doing the querying?

You need to pass a reference to the target object to the object from which you want to access it. This is sometimes necessary but it also means that you introduce a tight coupling between these two objects, which you generally want to avoid if you can. So think about each case and see if there are other possible designs.

Use this for Swift:

let window:UIWindow? = (UIApplication.sharedApplication().delegate?.window)!

Swift 3

    if let window = NSApplication.shared().windows.first {
        // access window. properties now
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!