如何在 iOS 中创建 AppDelegate 共享实例?

How to create AppDelegate shared Instance in iOS?

如何创建 sharedInstanceAppDelegate 并在我的应用程序中的任何地方使用。

这样使用:

在AppDelegate.h

+ (AppDelegate *)sharedAppDelegate;

在AppDelegate.m

+ (AppDelegate *)sharedAppDelegate{
    return (AppDelegate *)[UIApplication sharedApplication].delegate;
}

使用这个:

+ (AppDelegate *)appDelegate
{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

在Constants.h

中声明语句
#define myappDelegate ((AppDelegate *)[[UIApplication sharedApplication] delegate])

如果您在 .pch 文件中声明 Constants.h,则可以在应用程序的任何位置使用 myappDelegate

Check this 用于 Xcode 6

的 PCH

每 ViewController 秒

使用这个
#import "AppDelegate.h"

  AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

或者您可以在 ViewController subclass 中创建一个方法并在每个 ViewController 中使用它。

-(AppDelegate*) app
{
   return (AppDelegate*) [[UIApplication sharedApplication] delegate];
}

在 UIViewController 的子class 中——然后将其作为所有视图控制器的基础class。

然后,[self app] 就可以使用了,您不必保留参考。

你可以像下面这样使用

在 Objective C 中:您可以在 .pch 文件和用户中添加以下行

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

并像 myAppDelegate.someVariable or [myAppDelegate somemethod]

一样使用

在Swift

Swift >= 1.2(在 Xcode 6.3 中引入)

let myAppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let aVariable = myAppDelegate.someVariable

Swift < 1.2

let myAppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let aVariable = myAppDelegate.someVariable

任何 ViewController 它正在运行此 appDelegate 包括 Xcode 8 也

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

其他答案使用 UIApplication.shared.delegate,但您需要始终写 'as! AppDelegate',因此 Swift 更简洁的代码:

// AppDelegate.swift

static var shared = AppDelegate() // Declare a static variable as an instance of AppDelegate

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    // Singleton
    AppDelegate.shared = self // set the value of "shared" to the current instance

    return true
}


用法

AppDelegate.shared