Iphone [[UIApplication sharedApplication]委托]的简写形式?

Iphone [[UIApplication sharedApplication]委托]的简写形式?,iphone,objective-c,delegates,singleton,Iphone,Objective C,Delegates,Singleton,我将全局变量存储在AppDelegate中,并通过以下方式访问它们: AppDelegate *d = [[UIApplication sharedApplication] delegate]; d.someString = ... 建议用什么方法来保存一些输入,这样我就不需要AppDelegate*d=[[UIApplication-sharedApplication]delegate]一次又一次?谢谢 由于您的应用程序委派从未真正更改,因此您可以创建一个在应用程序委派代码中定义的外部代理,

我将全局变量存储在AppDelegate中,并通过以下方式访问它们:

AppDelegate *d = [[UIApplication sharedApplication] delegate];
d.someString = ...

建议用什么方法来保存一些输入,这样我就不需要
AppDelegate*d=[[UIApplication-sharedApplication]delegate]一次又一次?谢谢

由于您的应用程序委派从未真正更改,因此您可以创建一个在应用程序委派代码中定义的外部代理,这与Mac OS X Cocoa应用程序的
NSApp
external非常类似

因此,请在AppDelegate头中定义外部代理(或在任何地方都包含的其他内容):

然后创建并在实现文件中进行设置:

AppDelegate* appDelegate = nil;

// later -- i can't recall the actual method name, but you get the idea
- (BOOL)applicationDidFinishLaunchingWithOptions:(NSDictionary*)options
{
  appDelegate = self;
  // do other stuff
  return YES;
}
然后其他类可以直接访问它:

#import "AppDelegate.h"

// later
- (void)doSomethingGreat
{
  NSDictionary* mySettings = [appDelegate settings];
  if( [[mySettings objectForKey:@"stupidOptionSet"] boolValue] ) {
    // do something stupid
  }
}

您可以创建一个C风格的宏,并将其放在某个头文件中

(至于将app delegate用作一个巨大的全局变量catch all,那又是另一天的咆哮。)

我创建了一个名为UIApplication+delegate的应用程序,其中包含一些方便的消息。获取我的特定委托是方便信息之一。因此,例如,如果我的应用程序委托被称为MyAppDelegate,它将如下所示:

#define AppDelegate (YourAppDelegate *)[[UIApplication sharedApplication] delegate]
[AppDelegate ......];
UIApplication+delegate.h

#import "MyAppDelegate.h"

@interface UIApplication(delegate)
+ (MyAppDelegate *)thisApp;
@end
UIApplication+delegate.m

#import "UIApplication+delegate.h"


@implementation UIApplication(delegate)

+ (MyAppDelegate *)thisApp {
    return (MyAppDelegate*)[[UIApplication sharedApplication] delegate];
}

@end
在需要委托的类中,我执行以下操作:

#import "UIApplication+delegate.h"

...

- (void)doStuff {
    MyAppDelegate *app = [UIApplication thisApp];
    // use "app"
}
正如Shaggy Frog所说,在YourAppDelegate.h文件中定义一个宏,例如:

#define AppDelegate (YourAppDelegate *)[[UIApplication sharedApplication] delegate]
[AppDelegate ......];
然后,您可以在代码中获得应用程序委托,如下所示:

#define AppDelegate (YourAppDelegate *)[[UIApplication sharedApplication] delegate]
[AppDelegate ......];

我还创建了一个类别,只是我将我的类别应用于NSObject,这样应用程序中的任何对象都可以轻松访问委托





这个。这是最好的解决方案。你不需要像这样用括号括起来吗:?另外,确保“AppDelegate”和“YourAppDelegate”是不同的词。有时“YourAppDelegate”,即应用程序代理的名称默认为简单的“AppDelegate”。我更喜欢此解决方案,因为使用此解决方案的点符号访问器将应用程序代理导入pch文件。通过这样做,您不需要在每个文件中导入,并且可以在整个项目中的任何位置获取此宏。请注意,如果您键入
AppDelegate*d=[[UIApplication sharedApplication]delegate]一次又一次,这可能是一种代码气味。你真的需要app delegate来做app delegate之类的事情吗,还是你把它当作global state的垃圾场?