web-dev-qa-db-ja.com

[[UIApplication sharedApplication]デリゲート]の省略形?

AppDelegateにグローバル変数を保存し、次の方法でアクセスします。

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

タイピングを節約するための推奨される方法は何ですか。そのため、何度もAppDelegate *d = [[UIApplication sharedApplication] delegate];する必要はありませんか?ありがとう!

29
ohho

Shaggy Frogが言ったように、YourAppDelegate.hファイルでマクロを定義します。例は次のとおりです。

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

次に、次のようにコードでアプリデリゲートを取得できます。

[AppDelegate ......];
41
Nevin

アプリデリゲートが実際に変更されることはないため、Mac OS XCocoaアプリケーションのNSApp外部と非常によく似た、アプリデリゲートコードで定義する外部を作成できます。

したがって、AppDelegateヘッダー(またはどこにでも含める他の何か)で外部を定義します。

extern AppDelegate* 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
  }
}
11
Jason Coco

Cスタイルのマクロを作成して、ヘッダーファイルのどこかに置くことができます。

(アプリデリゲートを巨大なグローバル変数のキャッチオールとして使用することに関しては、それは別の日の別の怒りです。)

8
Shaggy Frog

category calledUIApplication + delegateを作成し、いくつかの便利なメッセージを含めます。私の特定の代理人を便利なメッセージの1つにする。したがって、たとえば、アプリデリゲートがMyAppDelegateと呼ばれた場合、次のようになります。

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"
}
4
Daniel

NSObjectに自分のオブジェクトを適用したことを除いて、カテゴリも作成しました。これにより、アプリケーション内のすべてのオブジェクトがデリゲートに簡単に到達できるようになります。


#import "MyAppDelegate.h"

@interface NSObject(delegate)
- (MyAppDelegate *) appDelegate;
@end

#import "NSObject+delegate.h"

@implementation UIApplication(delegate)

- (MyAppDelegate *)appDelegate {
    return (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
}

@end

2
drekka