如前所述——我是一名 Objective-C 新手,但在阅读了 4 本关于该主题的实体书以及大量电子书和文档后,我仍然找不到我要找的东西。
我有一个顶层内容 View Controller ,它想根据应用程序委托(delegate)的窗口属性的物理维度配置其 View 属性。这是一些人已经问过的问题。 ([UIScreen mainScreen]
由于之前在本论坛上多次播出的原因而没有将其删除)。因此,逻辑方法是让内容 View Controller 读取应用程序委托(delegate)窗口的框架。现在,我发现的唯一接近于此的答案是使用 [[[UIApplication sharedApplication] window] frame]
- 但是,这仅在 window 属性设置为 keyAndVisible 后才有效。内容 View Controller 需要在获取 makeKeyAndVisible 之前读取应用委托(delegate)的窗口属性。。代码按此顺序......
应用委托(delegate):
- (BOOL) application: (UIApplication *) application didFinishLaunchingWithOptions: (NSDictionary *) launchOptions {
// This next line is a test window frame for R&D purposes....
[self setWindow: [[UIWindow alloc] initWithFrame: CGRectMake(0.0f, 20.0f, 320.0f, 320.0f)]];
if ([self window]) {
contentViewController = [[ContentViewControl alloc] initWithNibName: nil bundle: nil]; // Content view controller instantiated here
if (contentViewController) {
[[self window] addSubview: [contentViewController view]];
[[self window] layoutSubviews];
[[self window] makeKeyAndVisible]; // Window made key and visible here
return YES;
}
}
return NO;
}
在我的内容 View Controller 的 initWithNibName: nil bundle: nil 方法中,我有以下测试代码...
- (id) initWithNibName: (NSString *) nibNameOrNil bundle: (NSBundle *) nibBundleOrNil {
self = [super initWithNibName: nibNameOrNil bundle: nibBundleOrNil];
if (self) {
NSLog(@"%@", NSStringFromCGRect([[[UIApplication sharedApplication] keyWindow] frame]));
// This does not work.
}
return self;
}
这不起作用,因为 App Delegate 的窗口还不是关键的和可见的。
所以,我的问题是这样;我的 App Delegate 类实例的名称是什么?我知道 App Delegate 的 Class 名称默认为 myApplicationNameAppDelegate
但我使用的是 instance 名称。我想用类似的东西替换对 [[UIApplication sharedApplication] keyWindow]
的调用;
[myAppDelegatesInstanceName window].
稍微扩展一下,一个人如何访问其他目标对象中的方法,这些目标对象不是执行查询的对象的范围后代?
就像我说的,我对这一切完全是菜鸟,这可能是另一个愚蠢的菜鸟问题,但似乎还没有人以简单的方式回答过这个问题。
(在程序上 - 我的主场 - 有很多方法可以将窗口的东西放到其他级别的范围内,从让整个程序套件全局访问窗口到通过各种方法将它作为特定参数传递下去功能层次结构——但这个客观的东西似乎背离了既定的程序实践)。
如果有人能提供帮助,我将不胜感激。这玩意绝对不直观! V.V.
最佳答案
您可以通过单例 UIApplication
实例访问应用委托(delegate):
[[[UIApplication sharedApplication] delegate] window];
不过,这是一种特殊情况,因为您可以访问一个对象(UIApplication
实例),您知道该对象的委托(delegate)就是您要访问的对象。一般情况:
Expanding this a little, how does one access methods in other target objects that are not scope descendants of the object doing the querying?
您需要将对目标对象的引用传递给您要从中访问它的对象。这有时是必要的,但这也意味着您在这两个对象之间引入了紧密耦合,如果可以的话,您通常希望避免这种情况。因此,请考虑每种情况,看看是否还有其他可能的设计。
关于ios - 如何从另一个对象访问我的 Application Delegate 的窗口访问器方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5760785/